An unfinished system to manage all your paper documentation in an easy way.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

autodoc.fcgi 11KB

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