An unfinished system to manage all your paper documentation in an easy way.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #!/usr/bin/perl
  2. use strict;
  3. use FCGI;
  4. use JSON;
  5. use DBI;
  6. use utf8;
  7. use GD::Simple;
  8. use Data::Dumper;
  9. use Data::UUID;
  10. use warnings;
  11. $Data::Dumper::Sortkeys = 1;
  12. my $conf = load_conf("../etc/autodoc.json");
  13. my $dbh = sqlconnect($conf->{sql});
  14. my %map = (
  15. api_v1_POST_documents => \&api_v1_POST_documents,
  16. api_v1_POST_documents_id_data => \&api_v1_POST_documents_id_data,
  17. api_v1_GET_documents_id_image => \&api_v1_GET_documents_id_image,
  18. api_v1_GET_pages_id_image => \&api_v1_GET_pages_id_image,
  19. api_v1_GET_documents => \&api_v1_GET_documents,
  20. api_v1_GET_documents_id => \&api_v1_GET_documents_id,
  21. api_v1_GET_pages_id => \&api_v1_GET_pages_id,
  22. api_v1_PATCH_documents_id => \&api_v1_PATCH_documents_id,
  23. );
  24. my $request = FCGI::Request();
  25. while($request->Accept() >= 0) {
  26. my $user = $ENV{REMOTE_USER} || 'undefined';
  27. my $qs = parse_querystring($ENV{QUERY_STRING});
  28. my $method = $ENV{REQUEST_METHOD};
  29. # QS sanity check
  30. if ( exists $qs->{id} && $qs->{id} !~ /^\d+$/ ) {
  31. fatal_api_error(400,"invalid id");
  32. }
  33. if ( exists $qs->{maxWidth} && $qs->{maxWidth} !~ /^\d+$/ ) {
  34. fatal_api_error(400,"invalid maxWidth");
  35. }
  36. if ( exists $qs->{maxHeight} && $qs->{maxHeight} !~ /^\d+$/ ) {
  37. fatal_api_error(400,"invalid maxHeight");
  38. }
  39. if ( exists $qs->{pageSize} && $qs->{pageSize} !~ /^\d+$/ ) {
  40. fatal_api_error(400,"invalid pageSize");
  41. }
  42. if ( exists $qs->{pageIndex} && $qs->{pageIndex} !~ /^\d+$/ ) {
  43. fatal_api_error(400,"invalid pageIndex");
  44. }
  45. my $path = [ split(/\//,$ENV{SCRIPT_NAME}) ] if exists $ENV{SCRIPT_NAME};
  46. shift(@{$path});
  47. my $post = parse_post(
  48. \*STDIN,
  49. exists $ENV{CONTENT_LENGTH} ? $ENV{CONTENT_LENGTH} : 0,
  50. exists $ENV{CONTENT_TYPE} ? $ENV{CONTENT_TYPE} : 0
  51. );
  52. my($code, $hdr, $type, $data) = process_query($method, $path, $qs, $post, $user);
  53. print STDERR Dumper("code",$code,"hdr", $hdr, "type", $type, "data", $data);
  54. $hdr = [ ] if !defined $hdr;
  55. if ( defined $type ) {
  56. if ( $type eq 'application/json' ) {
  57. $data = to_json($data, { utf8 => 1, pretty => 1 });
  58. }
  59. }
  60. send_response($code, $hdr, $type, $data);
  61. }
  62. sub gen_uuid {
  63. my $ug = Data::UUID->new;
  64. return lc($ug->create_str());
  65. }
  66. sub send_response {
  67. my ($code, $hdr, $type, $data) = @_;
  68. printf("Status: %s\r\n", $code);
  69. printf("Content-type: %s\r\n", $type) if defined $type;
  70. printf("Content-length: %i\r\n", length($data)) if defined $data;
  71. foreach ( @{$hdr} ) { printf("%s\r\n",$_); }
  72. printf("\r\n");
  73. print $data if defined $data;
  74. }
  75. sub fatal_api_error {
  76. my($code,$hdr,$type,$body)=api_error(@_);
  77. print STDERR "AUTODOC_FATAL: $body\r\n";
  78. send_response($code, $hdr, $type, $body);
  79. exit;
  80. }
  81. sub load_conf {
  82. my($file) = @_;
  83. my $x='';
  84. open(F,"$file") || fatal_api_error(500,"Failed to load configuration file");
  85. while(<F>) { $x.=$_; }
  86. close(F);
  87. return from_json($x);
  88. }
  89. sub process_query {
  90. my($method, $path, $qs, $post, $user) = @_;
  91. my ($api_version, $path_main, $path_id, $path_sub) = @{$path};
  92. return api_error(404, "Unknown API version") if !defined $api_version;
  93. return api_error(405, "Unknown METHOD") if !defined $method;
  94. return api_error(404, "Unknown API function") if !defined $path_main;
  95. my $func = 'api_' . $api_version . '_' . $method . '_' . $path_main;
  96. $func .= '_id' if defined $path_id;
  97. $func .= '_'.$path_sub if defined $path_sub;
  98. return $map{$func}->($path_id, $qs, $post, $user) if exists $map{$func};
  99. return api_error(404, "Invalid path/method combination");
  100. }
  101. sub db_get_document_object {
  102. my($id) = @_;
  103. my $document;
  104. my @pages;
  105. my @pageids;
  106. my @tags;
  107. my $q = sqlquery($dbh, "SELECT * FROM documents WHERE id = ?", $id);
  108. while(my $hash = $q->fetchrow_hashref()) { $document = $hash; }
  109. $q = sqlquery($dbh, "
  110. SELECT p.*
  111. FROM pages p
  112. JOIN documents_pages dp
  113. ON p.id = dp.pageId
  114. WHERE dp.documentId = ?", $id);
  115. while(my $hash = $q->fetchrow_hashref()) {
  116. if ( $hash->{isprimary} ) {
  117. $document->{primary} = $hash->{id};
  118. }
  119. push @pages, $hash; push @pageids, $hash->{id};
  120. }
  121. $q = sqlquery($dbh, "
  122. SELECT tags.tag AS tag
  123. FROM documents_tags JOIN tags ON documents_tags.tagId = tags.id
  124. WHERE documentId = ? ORDER BY tag", $id);
  125. while(my ($tag) = $q->fetchrow_array()) { push @tags, $tag; }
  126. my %lang;
  127. foreach my $page ( @pages ) {
  128. $q = sqlquery($dbh, "
  129. SELECT
  130. SUM(pw.count) AS count,
  131. l.short AS short
  132. FROM pages_words pw
  133. JOIN words w ON pw.wordID = w.id
  134. JOIN lang l ON w.langId = l.id
  135. WHERE pw.pageId = ?
  136. GROUP BY l.id", $page->{id});
  137. while(my $h = $q->fetchrow_hashref()) {
  138. $lang{$h->{short}}=$h->{count};
  139. }
  140. }
  141. if ( defined $document ) {
  142. my $out = {
  143. id => $document->{id},
  144. pageId => [ @pageids ],
  145. primaryPage => $document->{primary},
  146. name => $document->{name},
  147. created => $document->{created},
  148. owner => $document->{owner},
  149. status => $document->{status},
  150. languages => [ keys %lang ],
  151. tags => [ @tags ],
  152. };
  153. return (200, undef, "application/json", $out);
  154. }
  155. return (404, undef, "application/json", "");
  156. }
  157. sub db_get_page_object {
  158. my($id) = @_;
  159. my $out;
  160. my %lang;
  161. my $q = sqlquery($dbh, "SELECT * FROM pages_lang WHERE pageId = ?", $id);
  162. while(my $hash = $q->fetchrow_hashref()) {
  163. $lang{$hash->{language}}++;
  164. }
  165. $q = sqlquery($dbh, "SELECT * FROM pages WHERE documentId = ?", $id);
  166. while(my $hash = $q->fetchrow_hashref()) {
  167. $out = {
  168. id => $id,
  169. documentId => $hash->{documentId},
  170. name => $hash->{name},
  171. created => $hash->{created},
  172. owner => $hash->{owner},
  173. status => $hash->{status},
  174. language => [ keys %lang ],
  175. };
  176. }
  177. if ( exists $out->{id} ) {
  178. return (200, "application/json", $out);
  179. }
  180. return (404, undef, "application/json", "");
  181. }
  182. sub get_page_image {
  183. my($id, $qs) = @_;
  184. my $wh;
  185. my $size;
  186. if ( exists $qs->{maxWidth} ) {
  187. $wh = 'w';
  188. $size = $qs->{maxWidth};
  189. }
  190. elsif ( exists $qs->{maxHeight} ) {
  191. $wh = 'h';
  192. $size = $qs->{maxWidth};
  193. }
  194. my $src;
  195. my $dst;
  196. if ( !defined $id ) {
  197. $src = sprintf("%s/%s",
  198. $conf->{path}{global}, $conf->{path}{error_img});
  199. }
  200. else {
  201. $src = sprintf("%s/%s/%s.jpeg",
  202. $conf->{path}{global}, $conf->{path}{original}, $id);
  203. }
  204. if ( defined $wh && defined $size ) {
  205. if ( defined $id ) {
  206. $dst = sprintf("%s/%s/%s-%s-%s.jpeg",
  207. $conf->{path}{global}, $conf->{path}{cache}, $id, $wh, $size);
  208. }
  209. else {
  210. $dst = sprintf("%s/%s/error_img-%s-%s.jpeg",
  211. $conf->{path}{global}, $conf->{path}{cache}, $wh, $size);
  212. }
  213. }
  214. else {
  215. if ( defined $id ) {
  216. $dst = sprintf("%s/%s/%s.jpeg",
  217. $conf->{path}{global}, $conf->{path}{cache}, $id);
  218. }
  219. else {
  220. $dst = sprintf("%s/%s/error_img.jpeg",
  221. $conf->{path}{global}, $conf->{path}{cache});
  222. }
  223. }
  224. my $imgfile;
  225. if ( !defined $dst ) {
  226. $imgfile = $src;
  227. }
  228. else {
  229. if ( ! -r $dst ) {
  230. my $cmd;
  231. if ( defined $wh && defined $size ) {
  232. $cmd = sprintf("convert %s -resize %s%s %s",
  233. $src,
  234. $wh eq 'h' ? 'x' : '',
  235. $size,
  236. $dst
  237. );
  238. }
  239. else {
  240. $cmd = sprintf("cp %s %s", $src, $dst);
  241. }
  242. print STDERR "CMD=$cmd\n";
  243. system($cmd);
  244. }
  245. $imgfile = $dst;
  246. }
  247. my $url = $dst;
  248. $url =~ s/$conf->{path}{global}//;
  249. return $url;
  250. }
  251. # create an empty document object.
  252. sub api_v1_POST_documents {
  253. my($id, $qs, $post, $user) = @_;
  254. my $docid;
  255. my $q = sqlquery($dbh, "CALL create_document(?)", $user);
  256. while(my($id) = $q->fetchrow_array()) {
  257. $docid = $id;
  258. }
  259. return db_get_document_object($docid);
  260. }
  261. sub api_v1_POST_documents_id_data {
  262. my($id, $qs, $post, $user) = @_;
  263. my $uuid = gen_uuid();
  264. my $ext = $post->{ctype};
  265. $ext =~ s/.*\///;
  266. my $file = sprintf("%s/%s/%s_%s.%s",
  267. $conf->{path}{global},
  268. $conf->{path}{queue},
  269. $id, $uuid, $ext);
  270. open(F,'>'.$file);
  271. print F $post->{data};
  272. close(F);
  273. return (200, undef, "application/json", { })
  274. }
  275. # get document image/thumbnail
  276. sub api_v1_GET_documents_id_image {
  277. my($id, $qs, $post, $user) = @_;
  278. my $pageid;
  279. my $q = sqlquery($dbh, "CALL get_primary_page(?)", $id);
  280. while(my($myid)=$q->fetchrow_array()) {
  281. $pageid = $myid;
  282. }
  283. return api_v1_GET_pages_id_image($pageid, $qs, $post, $user);
  284. }
  285. # get page image/thumbnail
  286. sub api_v1_GET_pages_id_image {
  287. my($id, $qs, $post, $user) = @_;
  288. #return (200, "image/jpeg", get_page_image($id, $qs));
  289. my $url = get_page_image($id, $qs);
  290. return (302, [ "Location: $url" ]);
  291. }
  292. # get a list of document objects
  293. sub api_v1_GET_documents {
  294. my($id, $qs, $post, $user) = @_;
  295. $qs->{pageSize} = $conf->{query}{pageSize} if !exists $qs->{pageSize};
  296. $qs->{pageIndex} = $conf->{query}{pageIndex} if !exists $qs->{pageIndex};
  297. my @out;
  298. my $q = sqlquery($dbh, "SELECT id FROM documents LIMIT ?,?",
  299. $qs->{pageSize} * $qs->{pageIndex},
  300. $qs->{pageSize});
  301. while(my ($id) = $q->fetchrow_array()) {
  302. my ($code, $hdr, $ct, $body) = db_get_document_object($id);
  303. push @out, $body;
  304. }
  305. return (
  306. 200,
  307. undef,
  308. "application/json",
  309. \@out
  310. );
  311. }
  312. # get a single document object
  313. sub api_v1_GET_documents_id {
  314. my($id, $qs, $post, $user) = @_;
  315. return db_get_document_object($id);
  316. }
  317. # get a specific page
  318. sub api_v1_GET_pages_id {
  319. my($id, $qs, $post, $user) = @_;
  320. return db_get_page_object($id);
  321. }
  322. # change document properties
  323. sub api_v1_PATCH_documents_id {
  324. my($id, $qs, $post, $user) = @_;
  325. if ( exists $qs->{addTags} ) {
  326. my $tags = get_array($qs->{addTags});
  327. foreach my $tag ( @{$tags} ) {
  328. sqlquery($dbh, "CALL add_tag(?,?)", $id, $tag);
  329. }
  330. }
  331. if ( exists $qs->{deleteTags} ) {
  332. my $tags = get_array($qs->{deleteTags});
  333. foreach my $tag ( @{$tags} ) {
  334. sqlquery($dbh, "CALL delete_tag(?,?)", $id, $tag);
  335. }
  336. }
  337. if ( exists $qs->{name} ) {
  338. sqlquery($dbh, "UPDATE documents SET name = ? WHERE id = ?",
  339. $qs->{name}, $id);
  340. }
  341. if ( exists $qs->{primarypage} ) {
  342. sqlquery($dbh, "CALL set_primary_page(?)", $qs->{primarypage});
  343. }
  344. return (200);
  345. }
  346. sub get_array {
  347. my($x) = @_;
  348. my @arr;
  349. if ( ref $x eq 'ARRAY' ) {
  350. @arr = @{$x};
  351. }
  352. else {
  353. @arr = [ $x ];
  354. }
  355. return \@arr;
  356. }
  357. sub api_error {
  358. my($code, $text)=@_;
  359. my %deftext = (
  360. "000" => "An error produced an internal error, cascading errors over errors",
  361. "404" => "No such API path"
  362. );
  363. $code = "000" if !defined $code;
  364. $text = $deftext{$code} if ( !defined $text || $code eq "000" );
  365. return ( $code, undef, "text/plain", $text . "\r\n" );
  366. }
  367. sub parse_querystring {
  368. my($in) = @_;
  369. my %out;
  370. if ( defined $in && length $in ) {
  371. foreach(split(/&/,$in)) {
  372. my($name,$value) = split(/=/);
  373. $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  374. # handle arrays
  375. if ( exists $out{$name} ) {
  376. if ( ! ref $out{$name} ) {
  377. my $old = $out{$name};
  378. $out{$name} = [ $old ];
  379. }
  380. push @{$out{$name}}, $value;
  381. }
  382. else {
  383. $out{$name}=$value;
  384. }
  385. }
  386. }
  387. return \%out;
  388. }
  389. sub parse_post {
  390. my($fd, $len, $ct) = @_;
  391. my $data = '';
  392. while ( $len > 0 ) {
  393. my $buf;
  394. my $read = read($fd, $buf, $len);
  395. $len -= $read;
  396. $data .= $buf;
  397. }
  398. if ( $ct eq 'application/json' ) {
  399. my $tmp = from_json($data);
  400. $data = $tmp;
  401. }
  402. return { ctype => $ct, len => $len, data => $data};
  403. }
  404. sub sqlconnect {
  405. my($sql) = @_;
  406. my $dsn = "DBI:mysql:database=$sql->{base};host=$sql->{host}";
  407. my $dbh = DBI->connect($dsn, $sql->{user}, $sql->{pass}, { mysql_enable_utf8 => 1 }) || \
  408. fatal_api_error(500,"Failed to connect to database");
  409. return $dbh;
  410. }
  411. sub sqlquery {
  412. my $dbh = shift;
  413. my $query = shift;
  414. my @args = @_;
  415. #print STDERR "$query\n";
  416. my $sth = $dbh->prepare($query) || fatal_api_error(500,"Failed to execute SQL query");
  417. $sth->execute(@args) || fatal_api_error(500,"Failed to execute SQL query");
  418. return $sth;
  419. }