forked from hayamiz/twittering-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwittering-http.el
1664 lines (1583 loc) · 65.8 KB
/
twittering-http.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; twittering-http.el --- Functions for making HTTP(S) requests in twittering-mode
;; Copyright (C) 2009-2015 Tadashi MATSUO
;; 2007, 2009-2011 Yuto Hayamizu.
;; 2008 Tsuyoshi CHO
;; 2014, 2015 Xavier Maillard
;; Author: Tadashi MATSUO <[email protected]>
;; Y. Hayamizu <[email protected]>
;; Tsuyoshi CHO <[email protected]>
;; Alberto Garcia <[email protected]>
;; Xavier Maillard <[email protected]>
;; Created: Sep 4, 2007
;; Version: HEAD
;; Identity: $Id: a2fc6eb695ad0994e986ab0413e53f335d9a947b $
;; Keywords: twitter web
;; URL: http://twmode.sf.net/
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; Functions for making HTTP(S) requests in twittering-mode
;;; Code:
(require 'twittering-utilities)
(defcustom twittering-use-ssl t
"*Use SSL connection if this variable is non-nil.
SSL connections use an external command as a backend."
:type 'boolean
:group 'twittering-mode)
(defcustom twittering-allow-insecure-server-cert nil
"*If non-nil, `twittering-mode' allows insecure server certificates."
:type 'boolean
:group 'twittering-mode)
(defvar twittering-curl-program nil
"Cache a result of `twittering-find-curl-program'.
DO NOT SET VALUE MANUALLY.")
(defvar twittering-curl-program-https-capability nil
"Cache a result of `twittering-start-http-session-curl-https-p'.
DO NOT SET VALUE MANUALLY.")
(defvar twittering-curl-program-http2-capability nil
"Cache a result of `twittering-start-http-session-curl-http2-p'.
DO NOT SET VALUE MANUALLY.")
(defvar twittering-wget-program nil
"Cache a result of `twittering-find-wget-program'.
DO NOT SET VALUE MANUALLY.")
(defcustom twittering-tls-program nil
"*List of strings containing commands to start TLS stream to a host.
Each entry in the list is tried until a connection is successful.
%h is replaced with server hostname, %p with port to connect to.
Also see `tls-program'.
If nil, this is initialized with a list of valied entries extracted from
`tls-program'."
:type '(repeat string)
:group 'twittering-mode)
(defcustom twittering-connection-type-order
'(curl wget urllib-http native urllib-https)
"*A list of connection methods in the preferred order."
:type 'list
:group 'twittering-mode)
(defvar twittering-notify-successful-http-get t)
(defun twittering-connection-build-customize-option ()
"Generate a valid `defcustom' entry to build `twittering-connection-type-table' variable."
(list 'repeat
(list
'cons :tag "Connection"
'(symbol :tag "Name" :value "")
'(repeat
:tag "Connection method definition"
(choice
(cons :tag "Check test method"
(const :format "" check)
(choice :value t (const :tag "Do not check" t)
(function :tag "Check function")))
(cons :tag "Display name"
(const :format "" display-name)
string)
(cons :tag "HTTPS connection method"
(const :format "" https)
(choice :value nil (const :tag "None" nil)
(const :tag "True" t)
(function :tag "HTTPS test function")))
(cons :tag "Send HTTP request function"
(const :format "" send-http-request)
function)
(cons :tag "Pre process buffer"
(const :format "" pre-process-buffer)
function))))))
(defcustom twittering-connection-type-table
'((native
(check . t)
(send-http-request . twittering-send-http-request-native)
(pre-process-buffer . twittering-pre-process-buffer-native))
(curl
(check . twittering-start-http-session-curl-p)
(https . twittering-start-http-session-curl-https-p)
(send-http-request . twittering-send-http-request-curl)
(pre-process-buffer . twittering-pre-process-buffer-curl))
(wget
(check . twittering-start-http-session-wget-p)
(https . ignore)
(send-http-request . twittering-send-http-request-wget)
(pre-process-buffer . twittering-pre-process-buffer-wget))
(urllib-http
(display-name . "urllib")
(check . twittering-start-http-session-urllib-p)
(https . nil)
(send-http-request . twittering-send-http-request-urllib)
(pre-process-buffer . twittering-pre-process-buffer-urllib))
(urllib-https
(display-name . "urllib")
(check . twittering-start-http-session-urllib-p)
(https . twittering-start-http-session-urllib-https-p)
(send-http-request . twittering-send-http-request-urllib)
(pre-process-buffer . twittering-pre-process-buffer-urllib)))
"A list of alist of connection methods."
:group 'twittering-mode
:type (twittering-connection-build-customize-option))
;;;
(defun twittering-percent-encode (str &optional coding-system)
"Encode STR according to Percent-Encoding defined in RFC 3986."
(twittering-oauth-url-encode str coding-system))
(defun twittering-lookup-connection-type (use-ssl &optional order table)
"Return available entry extracted fron connection type table.
TABLE is connection type table, which is an alist of type symbol and its
item alist, such as
'((native (check . t)
(https . twittering-start-http-session-native-tls-p)
(start . twittering-start-http-session-native))
(curl (check . twittering-start-http-session-curl-p)
(https . twittering-start-http-session-curl-https-p)
(start . twittering-start-http-session-curl))) .
ORDER means the priority order of type symbols.
If USE-SSL is nil, the item `https' is ignored.
When the type `curl' has priority and is available for the above table,
the function returns
'((check . twittering-start-http-session-curl-p)
(https . twittering-start-http-session-curl-https-p)
(start . twittering-start-http-session-curl)) ."
(let ((rest (or order twittering-connection-type-order))
(table (or table twittering-connection-type-table))
(result nil))
(while (and rest (null result))
(let* ((candidate (car rest))
(entry (cons `(symbol . ,candidate)
(cdr (assq candidate table))))
(entry (if (assq 'display-name entry)
entry
(cons `(display-name . ,(symbol-name candidate))
entry)))
(validate (lambda (item)
(let ((v (cdr (assq item entry))))
(or (null v) (eq t v) (functionp v)))))
(confirm (lambda (item)
(let ((v (cdr (assq item entry))))
(cond
((null v) nil)
((eq t v) t)
((functionp v) (funcall v)))))))
(if (and (funcall validate 'check)
(or (not use-ssl) (funcall validate 'https)))
(cond
((and (funcall confirm 'check)
(or (not use-ssl) (funcall confirm 'https)))
(setq rest nil)
(setq result entry))
(t
(setq rest (cdr rest))))
(message "The configuration for conncetion type `%s' is invalid."
candidate)
(setq rest nil))))
result))
(defun twittering-get-connection-method-name (use-ssl)
"Return a name of the preferred connection method.
If USE-SSL is non-nil, return a connection method for HTTPS.
If USE-SSL is nil, return a connection method for HTTP."
(cdr (assq 'display-name (twittering-lookup-connection-type use-ssl))))
(defun twittering-lookup-http-start-function (&optional order table)
"Decide a connection method from currently available methods."
(let ((entry
(twittering-lookup-connection-type twittering-use-ssl order table)))
(cdr (assq 'send-http-request entry))))
(defun twittering-ensure-connection-method (&optional order table)
"Ensure a connection method with a compromise.
Return nil if no connection methods are available with a compromise."
(let* ((use-ssl (or twittering-use-ssl twittering-oauth-use-ssl))
(entry (twittering-lookup-connection-type use-ssl order table)))
(cond
(entry
t)
((and (null entry) use-ssl
(yes-or-no-p "HTTPS(SSL) is unavailable. Use HTTP instead? "))
;; Fall back on connection without SSL.
(setq twittering-use-ssl nil)
(setq twittering-oauth-use-ssl nil)
(twittering-update-mode-line)
(twittering-ensure-connection-method order table))
(t
(message "No connection methods are available.")
nil))))
(defun twittering-make-http-request (method header-list host port path query-parameters post-body use-ssl)
"Returns an alist specifying a HTTP request.
METHOD specifies HTTP method. It must be \"GET\" or \"POST\".
HEADER-LIST is a list of (field-name . field-value) specifying HTTP header
fields. The fields \"Host\", \"User-Agent\" and \"Content-Length\" are
automatically filled if necessary.
HOST specifies the host.
PORT specifies the port. This must be an integer.
PATH specifies the absolute path in URI (without query string).
QUERY-PARAMTERS is a string or an alist.
If QUERY-PARAMTERS is a string, it is treated as an encoded query string.
If QUERY-PARAMTERS is an alist, it represents a list of cons pairs of
string, (query-key . query-value).
POST-BODY specifies the post body sent when METHOD equals to \"POST\".
If POST-BODY is nil, no body is posted.
If USE-SSL is non-nil, the request is performed with SSL.
The result alist includes the following keys, where a key is a symbol.
method: HTTP method such as \"GET\" or \"POST\".
scheme: the scheme name. \"http\" or \"https\".
host: the host to which the request is sent.
port: the port to which the request is sent (integer).
path: the absolute path string. Note that it does not include query string.
query-string: the query string.
encoded-query-alist: the alist consisting of pairs of encoded query-name and
encoded query-value.
uri: the URI. It includes the query string.
uri-without-query: the URI without the query string.
header-list: an alist specifying pairs of a parameter and its value in HTTP
header field.
post-body: the entity that will be posted."
(let* ((scheme (if use-ssl "https" "http"))
(default-port (if use-ssl 443 80))
(port (if port port default-port))
(query-string
(cond
((stringp query-parameters)
query-parameters)
((consp query-parameters)
(mapconcat (lambda (pair)
(cond
((stringp pair)
(twittering-percent-encode pair))
((consp pair)
(format
"%s=%s"
(twittering-percent-encode (car pair))
(twittering-percent-encode (cdr pair))))
(t
nil)))
query-parameters
"&"))
(t
nil)))
(encoded-query-alist
(cond
((stringp query-parameters)
;; Query name and its value must be already encoded.
(mapcar (lambda (str)
(if (string-match "=" str)
(let ((key (substring str 0 (match-beginning 0)))
(value (substring str (match-end 0))))
`(,key . ,value))
`(,str . nil)))
(split-string query-parameters "&")))
((consp query-parameters)
(mapcar (lambda (pair)
(cond
((stringp pair)
(cons (twittering-percent-encode pair) nil))
((consp pair)
(cons (twittering-percent-encode (car pair))
(twittering-percent-encode (cdr pair))))
(t
nil)))
query-parameters))
(t
nil)))
(uri-without-query
(concat scheme "://"
host
(when (and port (not (= port default-port)))
(format ":%d" port))
path))
(uri
(if query-string
(concat uri-without-query "?" query-string)
uri-without-query))
(header-list
`(,@(when (and (string= method "POST")
(not (assoc "Content-Length" header-list)))
`(("Content-Length" . ,(format "%d" (length post-body)))))
,@(unless (assoc "Host" header-list)
`(("Host" . ,host)))
,@(unless (assoc "User-Agent" header-list)
`(("User-Agent" . ,(twittering-user-agent))))
,@header-list)))
(cond
((not (member method '("POST" "GET")))
(error "Unknown HTTP method: %s" method)
nil)
((not (string-match "^/" path))
(error "Invalid HTTP path: %s" path)
nil)
(t
`((method . ,method)
(scheme . ,scheme)
(host . ,host)
(port . ,port)
(path . ,path)
(query-string . ,query-string)
(encoded-query-alist . ,encoded-query-alist)
(uri . ,uri)
(uri-without-query . ,uri-without-query)
(header-list . ,header-list)
(post-body . ,post-body))))))
(defun twittering-make-http-request-from-uri (method header-list uri &optional post-body)
"Returns an alist specifying a HTTP request.
The result alist has the same form as an alist generated by
`twittering-make-http-request'.
METHOD specifies HTTP method. It must be \"GET\" or \"POST\".
HEADER-LIST is a list of (field-name . field-value) specifying HTTP header
fields. The fields \"Host\" and \"User-Agent\" are automatically filled
if necessary.
URI specifies the URI including query string.
POST-BODY specifies the post body sent when METHOD equals to \"POST\".
If POST-BODY is nil, no body is posted."
(let* ((parts-alist
(let ((parsed-url (url-generic-parse-url uri)))
;; This is required for the difference of url library
;; distributed with Emacs 22 and 23.
(cond
((and (fboundp 'url-p) (url-p parsed-url))
;; Emacs 23 and later.
`((scheme . ,(url-type parsed-url))
(host . ,(url-host parsed-url))
(port . ,(url-portspec parsed-url))
(path . ,(url-filename parsed-url))))
((vectorp parsed-url)
;; Emacs 22.
`((scheme . ,(aref parsed-url 0))
(host . ,(aref parsed-url 3))
(port . ,(aref parsed-url 4))
(path . ,(aref parsed-url 5))))
(t
nil))))
(path (let ((path (cdr (assq 'path parts-alist))))
(if (string-match "\\`\\(.*\\)\\?" path)
(match-string 1 path)
path)))
(query-string (let ((path (cdr (assq 'path parts-alist))))
(if (string-match "\\?\\(.*\\)\\'" path)
(match-string 1 path)
nil))))
(twittering-make-http-request method header-list
(cdr (assq 'host parts-alist))
(cdr (assq 'port parts-alist))
path
query-string
post-body
(string= "https"
(cdr (assq 'scheme parts-alist))))))
(defun twittering-make-connection-info (request &optional additional order table)
"Make an alist specifying the information of connection for REQUEST.
REQUEST must be an alist that has the same keys as that generated by
`twittering-make-http-request'.
ADDITIONAL is appended to the tail of the result alist.
Following ADDITIONAL, an entry in TABLE is also appended to the result alist,
where `twittering-lookup-connection-type' determines the entry according to
the priority order ORDER.
If ORDER is nil, `twittering-connection-type-order' is used in place of ORDER.
If TABLE is nil, `twittering-connection-type-table' is used in place of TABLE.
The parameter symbols are following:
use-ssl: whether SSL is enabled or not.
allow-insecure-server-cert: non-nil if an insecure server certificate is
allowed on SSL.
cacert-file-fullpath: the full-path of a file including the certificates
authorizing a server certificate on SSL. The file must be in PEM format.
use-proxy: non-nil if using a proxy.
proxy-server: a proxy server or nil.
proxy-port: a port for connecting the proxy (integer) or nil.
proxy-user: a username for connecting the proxy or nil.
proxy-password: a password for connecting the proxy or nil.
request: an alist specifying a HTTP request."
(let* ((order (or order twittering-connection-type-order))
(table (or table twittering-connection-type-table))
(scheme (cdr (assq 'scheme request)))
(use-ssl (string= "https" scheme))
(entry (twittering-lookup-connection-type use-ssl order table)))
`((use-ssl . ,use-ssl)
(allow-insecure-server-cert
. ,twittering-allow-insecure-server-cert)
(cacert-file-fullpath
. ,(when use-ssl (twittering-ensure-ca-cert)))
(use-proxy . ,twittering-proxy-use)
,@(when twittering-proxy-use
`((proxy-server . ,(twittering-proxy-info scheme 'server))
(proxy-port . ,(twittering-proxy-info scheme 'port))
(proxy-user . ,(twittering-proxy-info scheme 'user))
(proxy-password . ,(twittering-proxy-info scheme 'password))))
(request . ,request)
,@additional
,@entry)))
(defun twittering-get-response-header (buffer)
"Extract HTTP response header from HTTP response.
BUFFER may be a buffer or the name of an existing buffer which contains the HTTP response."
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
(if (search-forward-regexp "\r?\n\r?\n" nil t)
(prog1
(buffer-substring (point-min) (match-end 0))
(when twittering-debug-mode
(debug-printf "connection-info=%s\n" connection-info)
(debug-print "HTTP response header:\n--BEGIN\n")
(debug-print (buffer-substring (point-min) (match-end 0)))
(debug-print "--END\n")))
nil))))
(defun twittering-make-header-info-alist (header-str)
"Make HTTP header alist from HEADER-STR.
The alist consists of pairs of field-name and field-value, such as
'((\"Content-Type\" . \"application/xml\; charset=utf-8\")
(\"Content-Length\" . \"2075\"))."
(let* ((lines (split-string header-str "\r?\n"))
(status-line (car lines))
(header-lines (cdr lines)))
(when (string-match
"^\\(HTTP/1\\.[01]\\|HTTP/2\\(?:\\.0\\)?\\) \\([0-9][0-9][0-9]\\)\\(.*\\)$"
status-line)
(append `((status-line . ,status-line)
(http-version . ,(match-string 1 status-line))
(status-code . ,(match-string 2 status-line))
(reason-phrase . ,(match-string 3 status-line)))
(remove nil
(mapcar
(lambda (line)
(when (string-match "^\\([^: ]*\\): *\\(.*\\)$" line)
(cons (match-string 1 line) (match-string 2 line))))
header-lines))))))
(defun twittering-get-content-subtype-symbol-from-header-info (header-info)
"Return a symbol corresponding to the subtype of content-type."
(let* ((content-type
;; According to RFC2616, field name of a HTTP header is
;; case-insensitive.
(car
(remove
nil
(mapcar (lambda (entry)
(when (and (stringp (car entry))
(let ((case-fold-search t))
(string-match "\\`content-type\\'"
(car entry))))
(cdr entry)))
header-info))))
(subtype (when (and (stringp content-type)
(string-match "\\` *[^/]*/\\([^ ;]*\\)"
content-type))
(downcase (match-string 1 content-type))))
(symbol-alist
'(("json" . json)
("atom+xml" . atom)
("xml" . xml))))
(cdr (assoc subtype symbol-alist))))
(defun twittering-decode-response-body (header-info)
"Decode the current buffer according to the content-type in HEADER-INFO."
(let* ((content-type
;; According to RFC2616, field name of a HTTP header is
;; case-insensitive.
(car
(remove
nil
(mapcar (lambda (entry)
(when (and (stringp (car entry))
(let ((case-fold-search t))
(string-match "\\`content-type\\'"
(car entry))))
(cdr entry)))
header-info))))
(parameters (when (stringp content-type)
(cdr (split-string content-type ";"))))
(regexp "^[[:space:]]*charset=utf-8[[:space:]]*$")
(encoded-with-utf-8
(let ((case-fold-search t))
(remove nil
(mapcar (lambda (entry)
(string-match regexp entry))
parameters)))))
(when encoded-with-utf-8
(decode-coding-region (point-min) (point-max) 'utf-8))))
(defun twittering-send-http-request-internal (request additional-info sentinel &optional order table)
"Open a connection and return a subprocess object for the connection.
REQUEST must be an alist that has the same keys as that generated by
`twittering-make-http-request'.
SENTINEL is called as a function when the process changes state.
It gets three arguments: the process, a string describing the change, and
the connection-info, which is generated by `twittering-make-connection-info'
and also includes an alist ADDITIONAL-INFO.
How to perform the request is selected from TABLE according to the priority
order ORDER. ORDER and TABLE are directly sent to
`twittering-make-connection-info'.
If ORDER is nil, `twittering-connection-type-order' is used in place of ORDER.
If TABLE is nil, `twittering-connection-type-table' is used in place of TABLE.
"
(let* ((order (or order twittering-connection-type-order))
(table (or table twittering-connection-type-table))
(connection-info
(twittering-make-connection-info request additional-info
order table))
(func (cdr (assq 'send-http-request connection-info)))
(temp-buffer (generate-new-buffer "*twmode-http-buffer*"))
;; Bind `default-directory' to the temporary directory
;; because it is possible that the directory pointed by
;; `default-directory' has been already removed.
(default-directory temporary-file-directory))
(cond
((and func (functionp func))
(funcall func "*twmode-generic*" temp-buffer
connection-info
(when (and sentinel (functionp sentinel))
(lexical-let ((sentinel sentinel)
(connection-info connection-info))
(lambda (proc status)
(apply sentinel proc status connection-info nil))))))
(t
(error "No valid connection method is found")
nil))))
(defun twittering-send-http-request (request additional-info func &optional clean-up-func)
"Send a HTTP request and return a subprocess object for the connection.
REQUEST must be an alist that has the same keys as that generated by
`twittering-make-http-request'.
FUNC is called when a HTTP response has been received without errors.
It is called with the current buffer containing the HTTP response (without
HTTP headers). FUNC is called with four arguments: the process, a symbol
describing the status of the process, a connection-info generated by
`twittering-make-connection-info', and a header-info generated by
`twittering-get-response-header' and `twittering-make-header-info-alist'.
The connection-info also includes an alist ADDITIONAL-INFO.
If FUNC returns non-nil and `twittering-buffer-related-p' is non-nil, the
returned value is displayed as a message.
And also, if FUNC returns a string and it matches the regular expression
\"^\\\\(Failuare\\\\|Response\\\\): \", the returned value is displayed
as a message.
CLEAN-UP-FUNC is called whenever the sentinel of the subprocess for the
connection is called (as `set-process-sentinel').
It is called with three arguments: the process, a symbol describing the status
of the proess, and a connection-info generated by
`twittering-make-connection-info'.
They are the same as arguments for FUNC.
When a HTTP response has been received, FUNC is called in advance of
CLEAN-UP-FUNC. CLEAN-UP-FUNC can overwrite the message displayed by FUNC.
If the subprocess has exited, the buffer bound to it is automatically killed
after calling CLEAN-UP-FUNC.
The method to perform the request is determined from
`twittering-connection-type-table' according to the priority order
`twittering-connection-type-order'."
(lexical-let ((func func)
(clean-up-func clean-up-func))
(twittering-send-http-request-internal
request additional-info
(lambda (proc status-str connection-info)
(let ((status (cond
((string= status-str "urllib-finished") 'exit)
((processp proc) (process-status proc))
(t nil)))
(buffer (process-buffer proc))
(exit-status (cond
((string= status-str "urllib-finished") 0)
((processp proc) (process-exit-status proc))
(t 1)))
(command (process-command proc))
(pre-process-func
(cdr (assq 'pre-process-buffer connection-info)))
(mes nil))
(unwind-protect
(setq mes
(cond
((null status)
(format "Failure: process %s does not exist" proc))
((or (memq status '(run stop open listen connect))
(not (memq status '(exit signal closed failed))))
;; If the process is running, FUNC is not called.
nil)
((and command
(not (= 0 exit-status)))
;; If the process abnormally exited,
(format "Failure: %s exited abnormally (exit-status=%s)"
(car command) exit-status))
((not (buffer-live-p buffer))
(format "Failure: the buffer for %s is already killed"
proc))
(t
(when (functionp pre-process-func)
;; Pre-process buffer.
(funcall pre-process-func proc buffer connection-info))
(let* ((header (twittering-get-response-header buffer))
(header-info
(and header
(twittering-make-header-info-alist header))))
(with-current-buffer buffer
(goto-char (point-min))
(when (search-forward-regexp "\r?\n\r?\n" nil t)
;; delete HTTP headers.
(delete-region (point-min) (match-end 0)))
;; It may be necessary to decode the contents of
;; the buffer by UTF-8 because
;; `twittering-http-application-headers' specifies
;; utf-8 as one of acceptable charset.
;; For the present, only UTF-8 is taken into account.
(twittering-decode-response-body header-info)
(apply func proc status connection-info
header-info nil))))))
;; unwind-forms
(setq mes
(cond
((null mes)
nil)
((string-match "^\\(Failure\\|Response\\): " mes)
(let* ((request (cdr (assq 'request connection-info)))
(method (cdr (assq 'method request)))
(uri (cdr (assq 'uri request))))
(concat mes " for " method " " uri)))
((twittering-buffer-related-p)
mes)))
(when mes
;; CLEAN-UP-FUNC can overwrite a message from the return value
;; of FUNC.
(message "%s" mes))
(when (functionp clean-up-func)
(funcall clean-up-func proc status connection-info))
(when (and (memq status '(exit signal closed failed))
(buffer-live-p buffer)
(not twittering-debug-mode))
(kill-buffer buffer))))))))
(eval-when-compile (require 'tls nil t))
(defun twittering-start-http-session-native-tls-p ()
(when (and (not twittering-proxy-use)
(require 'tls nil t))
(unless twittering-tls-program
(let ((programs
(remove nil
(mapcar (lambda (cmd)
(when (string-match "\\`\\([^ ]+\\) " cmd)
(when (executable-find (match-string 1 cmd))
cmd)))
tls-program))))
(setq twittering-tls-program
(if twittering-allow-insecure-server-cert
(mapcar
(lambda (str)
(cond
((string-match "^\\([^ ]*/\\)?openssl s_client " str)
(concat (match-string 0 str) "-verify 0 "
(substring str (match-end 0))))
((string-match "^\\([^ ]*/\\)?gnutls-cli " str)
(concat (match-string 0 str) "--insecure "
(substring str (match-end 0))))
(t
str)))
programs)
programs))))
(not (null twittering-tls-program))))
;; TODO: proxy
(defun twittering-send-http-request-native (name buffer connection-info sentinel)
(let* ((request (cdr (assq 'request connection-info)))
(uri (cdr (assq 'uri connection-info)))
(method (cdr (assq 'method request)))
(scheme (cdr (assq 'scheme request)))
(host (cdr (assq 'host request)))
(port (cdr (assq 'port request)))
(path (cdr (assq 'path request)))
(query-string (cdr (assq 'query-string request)))
(post-body (cdr (assq 'post-body request)))
(use-proxy (cdr (assq 'use-proxy connection-info)))
(proxy-server (cdr (assq 'proxy-server connection-info)))
(proxy-port (cdr (assq 'proxy-port connection-info)))
(proxy-user (cdr (assq 'proxy-user connection-info)))
(proxy-password (cdr (assq 'proxy-password connection-info)))
(proxy-credentials
(when (and proxy-user proxy-password)
(concat "Basic "
(base64-encode-string
(concat proxy-user ":" proxy-password)))))
(header-list
(let ((original-header-list (cdr (assq 'header-list request))))
(if proxy-credentials
(cons
`("Proxy-Authorization" ,proxy-credentials)
original-header-list)
original-header-list)))
(use-ssl (cdr (assq 'use-ssl connection-info)))
(allow-insecure-server-cert
(cdr (assq 'allow-insecure-server-cert connection-info)))
(connect-host (or proxy-server host))
(connect-port (or proxy-port port))
(request-str
(format "%s %s HTTP/1.1\r\n%s\r\n\r\n%s\r\n"
method
(if use-proxy
;; As described in 5.1.2 of RFC2616, the
;; absolute URI is required here if the connection
;; uses a proxy.
uri
(concat path
(when query-string
(concat "?" query-string))))
(mapconcat (lambda (pair)
(format "%s: %s" (car pair) (cdr pair)))
header-list "\r\n")
(or post-body "")))
(coding-system-for-read 'binary)
(coding-system-for-write 'binary)
(tls-program twittering-tls-program)
(proc
(funcall (if use-ssl
'open-tls-stream
'open-network-stream)
"network-connection-process"
nil connect-host connect-port)))
(when proc
(set-process-buffer proc buffer)
(when (functionp sentinel)
(if (twittering-process-alive-p proc)
(set-process-sentinel proc sentinel)
(funcall sentinel proc "finished")))
(process-send-string proc request-str)
proc)))
(defun twittering-pre-process-buffer-native (proc buffer connection-info)
(let ((use-ssl (cdr (assq 'use-ssl connection-info)))
(args (process-command proc)))
(cond
((and use-ssl args
(car
(remove nil
(mapcar (lambda (cmd)
(string-match "^\\(.*/\\)?gnutls-cli\\b" cmd))
args))))
(with-current-buffer buffer
(save-excursion
(goto-char (point-max))
(when (search-backward-regexp
"- Peer has closed the GNUTLS connection\r?\n\\'")
(let ((beg (match-beginning 0))
(end (match-end 0)))
(delete-region beg end))))))
((and use-ssl args
(car
(remove nil
(mapcar
(lambda (cmd)
(string-match "^\\(.*/\\)?openssl s_client\\b" cmd))
args))))
(with-current-buffer buffer
(save-excursion
(goto-char (point-max))
(when (search-backward-regexp "closed\r?\n\\'")
(let ((beg (match-beginning 0))
(end (match-end 0)))
(delete-region beg end))))))
(t
nil))))
;;;;
;;;; HTTP functions for twitter-like service
;;;;
(defun twittering-http-application-headers (&optional method headers)
"Return an assoc list of HTTP headers for twittering-mode."
(unless method
(setq method "GET"))
(let ((headers headers))
(push (cons "User-Agent" (twittering-user-agent)) headers)
(when (string= "GET" method)
(push (cons "Accept"
(concat
"text/xml"
",application/xml"
",application/xhtml+xml"
",application/html;q=0.9"
",text/plain;q=0.8"
",image/png,*/*;q=0.5"))
headers)
(push (cons "Accept-Charset" "utf-8;q=0.7,*;q=0.7")
headers))
(when (string= "POST" method)
(push (cons "Content-Type" "text/plain") headers))
headers
))
(defun twittering-add-application-header-to-http-request (request account-info)
"Make a new HTTP request based on REQUEST with the authorization header.
The authorization header is generated from ACCOUNT-INFO.
ACCOUNT-INFO must be an alist that includes the following keys;
\"screen_name\" and \"password\" if `twittering-auth-method' is 'basic,
\"screen_name\", \"oauth_token\" and \"oauth_token_secret\" if
`twittering-auth-method' is 'oauth or 'xauth."
(let* ((method (cdr (assq 'method request)))
(auth-str
(cond
((eq twittering-auth-method 'basic)
(twittering-make-basic-authentication-string account-info))
((memq twittering-auth-method '(oauth xauth))
(twittering-make-oauth-authentication-string account-info request))
(t
nil)))
(cookie-str (twittering-make-cookie-string request account-info))
(application-headers
`(,@(twittering-http-application-headers method)
("Authorization" . ,auth-str)
,@(when cookie-str
`(("Cookie" . ,cookie-str))))))
(mapcar (lambda (entry)
(if (eq (car entry) 'header-list)
`(header-list
. ,(append (cdr entry) application-headers))
entry))
request)))
(defun twittering-get-error-message (header-info connection-info &optional buffer)
"Return an error message generated from the arguments.
HEADER-INFO must be an alist generated by `twittering-get-response-header'.
CONNECTION-INFO must be an alist generated by
`twittering-make-connection-info'. It may include some additional information
which is added by `twittering-send-http-request'.
BUFFER must be nil or a HTTP response body, which includes error messages from
the server when the HTTP status code equals to 400 or 403.
If BUFFER is nil, the current buffer is used instead."
(let ((buffer (or buffer (current-buffer)))
(status-line (cdr (assq 'status-line header-info)))
(status-code (cdr (assq 'status-code header-info)))
(format
(twittering-get-content-subtype-symbol-from-header-info header-info)))
(cond
((and (buffer-live-p buffer)
(member status-code '("400" "401" "403" "404")))
;; Twitter returns an error message as a HTTP response body if
;; HTTP status is "400 Bad Request" or "403 Forbidden".
;; See "HTTP Response Codes and Errors | dev.twitter.com"
;; http://dev.twitter.com/pages/responses_errors .
;;
;; However, Twitter seems to return an error message even when
;; the HTTP status is "401 Unauthorized" or "404 Not Found".
(let* ((error-mes
(cond
((eq format 'xml)
(let ((xmltree
(with-current-buffer buffer
(twittering-xml-parse-region (point-min)
(point-max)))))
(car (cddr (assq 'error (or (assq 'errors xmltree)
(assq 'hash xmltree)))))))
((eq format 'json)
(let ((json-object (with-current-buffer buffer
(twittering-json-read))))
(cdr (assq 'error json-object))))
(t
;; ATOM is not supported.
nil))))
(if error-mes
(format "%s (%s)" status-line error-mes)
status-line)))
(t
status-line))))
(defun twittering-http-get (account-info-alist host method &optional parameters format additional-info sentinel clean-up-sentinel)
"Send a HTTP GET request with application headers.
ACCOUNT-INFO-ALIST is an alist used by
`twittering-add-application-header-to-http-request'.
The alist made by `((account-info . ,ACCOUNT-INFO-ALIST) ,@ADDITIONAL-INFO)'
is used as the argument `additional-info' of `twittering-send-http-request'.
HOST is hostname of remote side, api.twitter.com (or search.twitter.com).
METHOD must be one of Twitter API method classes
(statuses, users or direct_messages).
PARAMETERS is alist of URI parameters.
ex) ((\"mode\" . \"view\") (\"page\" . \"6\")) => <URI>?mode=view&page=6
FORMAT is a response data format (\"xml\", \"atom\", \"json\")"
(let* ((format (or format "xml"))
(sentinel
(lexical-let ((sentinel (or sentinel
'twittering-http-get-default-sentinel)))
(lambda (proc status connection-info header-info)
(twittering-update-server-info connection-info header-info)
(apply sentinel proc status connection-info header-info nil))))
(path (concat "/" method "." format))
(headers nil)
(port nil)
(post-body "")
(request
(twittering-add-application-header-to-http-request
(twittering-make-http-request "GET" headers host port path
parameters post-body
twittering-use-ssl)
account-info-alist))
(additional-info
`((account-info . ,account-info-alist)
,@additional-info)))
(twittering-send-http-request request additional-info
sentinel clean-up-sentinel)))
(defun twittering-http-get-default-sentinel (proc status connection-info header-info)
(let ((status-line (cdr (assq 'status-line header-info)))
(status-code (cdr (assq 'status-code header-info)))
(format
(twittering-get-content-subtype-symbol-from-header-info header-info)))
(twittering-case-string
status-code
(("200")
(debug-printf "connection-info=%s" connection-info)
(let* ((spec (cdr (assq 'timeline-spec connection-info)))
(spec-string (cdr (assq 'timeline-spec-string connection-info)))
(service-method (cdr (assq 'service-method connection-info)))
(statuses
(cond
((eq format 'json)
(let ((json-array (twittering-json-read)))
(cond
((null json-array)
nil)
((eq (car spec) 'search)
(cond
((memq service-method '(twitter statusnet))
(mapcar 'twittering-json-object-to-a-status-on-search
(cdr (assq 'results json-array))))
((eq service-method 'twitter-api-v1.1)
(mapcar 'twittering-json-object-to-a-status
(cdr (assq 'statuses json-array))))))
((twittering-timeline-spec-is-direct-messages-p spec)
(mapcar
'twittering-json-object-to-a-status-on-direct-messages
json-array))
(t
(mapcar 'twittering-json-object-to-a-status
json-array)))))
((eq format 'xml)
(let ((xmltree
(twittering-xml-parse-region (point-min) (point-max))))
(when xmltree
(twittering-xmltree-to-status xmltree))))
((eq format 'atom)
(let ((xmltree
(twittering-xml-parse-region (point-min) (point-max))))
(when xmltree
(twittering-atom-xmltree-to-status xmltree))))
(t
nil)))
(rendered-tweets nil))
(let ((updated-timeline-info
(twittering-add-statuses-to-timeline-data statuses spec))
(buffer (twittering-get-buffer-from-spec spec)))