An unfinished system to manage all your paper documentation in an easy way.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

autodoc.fcgi 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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_image => \&api_v1_GET_pages_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. push @pages, $hash; push @pageids, $hash->{id};
  116. }
  117. $q = sqlquery($dbh, "
  118. SELECT tags.tag AS tag
  119. FROM documents_tags JOIN tags ON documents_tags.tagId = tags.id
  120. WHERE documentId = ? ORDER BY tag", $id);
  121. while(my ($tag) = $q->fetchrow_array()) { push @tags, $tag; }
  122. my %lang;
  123. foreach my $page ( @pages ) {
  124. $q = sqlquery($dbh, "
  125. SELECT
  126. SUM(pw.count) AS count,
  127. l.short AS short
  128. FROM pages_words pw
  129. JOIN words w ON pw.wordID = w.id
  130. JOIN lang l ON w.langId = l.id
  131. WHERE pw.pageId = ?
  132. GROUP BY l.id", $page->{id});
  133. while(my $h = $q->fetchrow_hashref()) {
  134. $lang{$h->{short}}=$h->{count};
  135. }
  136. }
  137. if ( defined $document ) {
  138. my $out = {
  139. id => $document->{id},
  140. pageId => [ @pageids ],
  141. name => $document->{name},
  142. created => $document->{created},
  143. owner => $document->{owner},
  144. status => $document->{status},
  145. languages => [ keys %lang ],
  146. tags => [ @tags ],
  147. };
  148. return (200, undef, "application/json", $out);
  149. }
  150. return (404, undef, "application/json", "");
  151. }
  152. sub db_get_page_object {
  153. my($id) = @_;
  154. my $out;
  155. my %lang;
  156. my $q = sqlquery($dbh, "SELECT * FROM pages_lang WHERE pageId = ?", $id);
  157. while(my $hash = $q->fetchrow_hashref()) {
  158. $lang{$hash->{language}}++;
  159. }
  160. $q = sqlquery($dbh, "SELECT * FROM pages WHERE documentId = ?", $id);
  161. while(my $hash = $q->fetchrow_hashref()) {
  162. $out = {
  163. id => $id,
  164. documentId => $hash->{documentId},
  165. name => $hash->{name},
  166. created => $hash->{created},
  167. owner => $hash->{owner},
  168. status => $hash->{status},
  169. language => [ keys %lang ],
  170. };
  171. }
  172. if ( exists $out->{id} ) {
  173. return (200, "application/json", $out);
  174. }
  175. return (404, undef, "application/json", "");
  176. }
  177. sub get_page_image {
  178. my($id, $qs) = @_;
  179. my $wh;
  180. my $size;
  181. if ( exists $qs->{maxWidth} ) {
  182. $wh = 'w';
  183. $size = $qs->{maxWidth};
  184. }
  185. elsif ( exists $qs->{maxHeight} ) {
  186. $wh = 'h';
  187. $size = $qs->{maxWidth};
  188. }
  189. my $src;
  190. my $dst;
  191. if ( !defined $id ) {
  192. $src = sprintf("%s/%s",
  193. $conf->{path}{global}, $conf->{path}{error_img});
  194. }
  195. else {
  196. $src = sprintf("%s/%s/%s.jpeg",
  197. $conf->{path}{global}, $conf->{path}{original}, $id);
  198. }
  199. if ( defined $wh && defined $size ) {
  200. if ( defined $id ) {
  201. $dst = sprintf("%s/%s/%s-%s-%s.jpeg",
  202. $conf->{path}{global}, $conf->{path}{cache}, $id, $wh, $size);
  203. }
  204. else {
  205. $dst = sprintf("%s/%s/error_img-%s-%s.jpeg",
  206. $conf->{path}{global}, $conf->{path}{cache}, $wh, $size);
  207. }
  208. }
  209. my $imgfile;
  210. if ( !defined $dst ) {
  211. $imgfile = $src;
  212. }
  213. else {
  214. if ( ! -r $dst ) {
  215. my $cmd = sprintf("convert %s -resize %s%s %s",
  216. $src,
  217. $wh eq 'h' ? 'x' : '',
  218. $size,
  219. $dst
  220. );
  221. print STDERR "CMD=$cmd\n";
  222. system($cmd);
  223. }
  224. $imgfile = $dst;
  225. }
  226. my $url = $dst;
  227. $url =~ s/$conf->{path}{global}//;
  228. return $url;
  229. }
  230. # create an empty document object.
  231. sub api_v1_POST_documents {
  232. my($id, $qs, $post, $user) = @_;
  233. my $docid;
  234. my $q = sqlquery($dbh, "CALL create_document(?)", $user);
  235. while(my($id) = $q->fetchrow_array()) {
  236. $docid = $id;
  237. }
  238. return db_get_document_object($docid);
  239. }
  240. sub api_v1_POST_documents_id_data {
  241. my($id, $qs, $post, $user) = @_;
  242. my $uuid = gen_uuid();
  243. my $ext = $post->{ctype};
  244. $ext =~ s/.*\///;
  245. my $file = sprintf("%s/%s/%s_%s.%s",
  246. $conf->{path}{global},
  247. $conf->{path}{queue},
  248. $id, $uuid, $ext);
  249. open(F,'>'.$file);
  250. print F $post->{data};
  251. close(F);
  252. return (200, undef, "application/json", { })
  253. }
  254. # get document image/thumbnail
  255. sub api_v1_GET_documents_id_image {
  256. my($id, $qs, $post, $user) = @_;
  257. my $pageid;
  258. my $q = sqlquery($dbh, "CALL get_primary_page(?)", $id);
  259. while(my($myid)=$q->fetchrow_array()) {
  260. $pageid = $myid;
  261. }
  262. return api_v1_GET_pages_id_image($pageid, $qs, $post, $user);
  263. }
  264. # get page image/thumbnail
  265. sub api_v1_GET_pages_id_image {
  266. my($id, $qs, $post, $user) = @_;
  267. #return (200, "image/jpeg", get_page_image($id, $qs));
  268. my $url = get_page_image($id, $qs);
  269. return (302, [ "Location: $url" ]);
  270. }
  271. # get a list of document objects
  272. sub api_v1_GET_documents {
  273. my($id, $qs, $post, $user) = @_;
  274. $qs->{pageSize} = $conf->{query}{pageSize} if !exists $qs->{pageSize};
  275. $qs->{pageIndex} = $conf->{query}{pageIndex} if !exists $qs->{pageIndex};
  276. my @out;
  277. my $q = sqlquery($dbh, "SELECT id FROM documents LIMIT ?,?",
  278. $qs->{pageSize} * $qs->{pageIndex},
  279. $qs->{pageSize});
  280. while(my ($id) = $q->fetchrow_array()) {
  281. my ($code, $hdr, $ct, $body) = db_get_document_object($id);
  282. push @out, $body;
  283. }
  284. return (
  285. 200,
  286. undef,
  287. "application/json",
  288. \@out
  289. );
  290. }
  291. # get a single document object
  292. sub api_v1_GET_documents_id {
  293. my($id, $qs, $post, $user) = @_;
  294. return db_get_document_object($id);
  295. }
  296. # get a specific page
  297. sub api_v1_GET_pages_id {
  298. my($id, $qs, $post, $user) = @_;
  299. return db_get_page_object($id);
  300. }
  301. # change document properties
  302. sub api_v1_PATCH_documents_id {
  303. my($id, $qs, $post, $user) = @_;
  304. if ( exists $qs->{addTags} ) {
  305. my $tags = get_array($qs->{addTags});
  306. foreach my $tag ( @{$tags} ) {
  307. sqlquery($dbh, "CALL add_tag(?,?)", $id, $tag);
  308. }
  309. }
  310. if ( exists $qs->{deleteTags} ) {
  311. my $tags = get_array($qs->{deleteTags});
  312. foreach my $tag ( @{$tags} ) {
  313. sqlquery($dbh, "CALL delete_tag(?,?)", $id, $tag);
  314. }
  315. }
  316. if ( exists $qs->{name} ) {
  317. sqlquery($dbh, "UPDATE documents SET name = ? WHERE id = ?",
  318. $qs->{name}, $id);
  319. }
  320. if ( exists $qs->{primarypage} ) {
  321. sqlquery($dbh, "CALL set_primary_page(?)", $qs->{primarypage});
  322. }
  323. return (200);
  324. }
  325. sub get_array {
  326. my($x) = @_;
  327. my @arr;
  328. if ( ref $x eq 'ARRAY' ) {
  329. @arr = @{$x};
  330. }
  331. else {
  332. @arr = [ $x ];
  333. }
  334. return \@arr;
  335. }
  336. sub api_error {
  337. my($code, $text)=@_;
  338. my %deftext = (
  339. "000" => "An error produced an internal error, cascading errors over errors",
  340. "404" => "No such API path"
  341. );
  342. $code = "000" if !defined $code;
  343. $text = $deftext{$code} if ( !defined $text || $code eq "000" );
  344. return ( $code, undef, "text/plain", $text . "\r\n" );
  345. }
  346. sub parse_querystring {
  347. my($in) = @_;
  348. my %out;
  349. if ( defined $in && length $in ) {
  350. foreach(split(/&/,$in)) {
  351. my($name,$value) = split(/=/);
  352. $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  353. # handle arrays
  354. if ( exists $out{$name} ) {
  355. if ( ! ref $out{$name} ) {
  356. my $old = $out{$name};
  357. $out{$name} = [ $old ];
  358. }
  359. push @{$out{$name}}, $value;
  360. }
  361. else {
  362. $out{$name}=$value;
  363. }
  364. }
  365. }
  366. return \%out;
  367. }
  368. sub parse_post {
  369. my($fd, $len, $ct) = @_;
  370. my $data = '';
  371. while ( $len > 0 ) {
  372. my $buf;
  373. my $read = read($fd, $buf, $len);
  374. $len -= $read;
  375. $data .= $buf;
  376. }
  377. if ( $ct eq 'application/json' ) {
  378. my $tmp = from_json($data);
  379. $data = $tmp;
  380. }
  381. return { ctype => $ct, len => $len, data => $data};
  382. }
  383. sub sqlconnect {
  384. my($sql) = @_;
  385. my $dsn = "DBI:mysql:database=$sql->{base};host=$sql->{host}";
  386. my $dbh = DBI->connect($dsn, $sql->{user}, $sql->{pass}) || \\
  387. fatal_api_error(500,"Failed to connect to database");
  388. return $dbh;
  389. }
  390. sub sqlquery {
  391. my $dbh = shift;
  392. my $query = shift;
  393. my @args = @_;
  394. #print STDERR "$query\n";
  395. my $sth = $dbh->prepare($query) || fatal_api_error(500,"Failed to execute SQL query");
  396. $sth->execute(@args) || fatal_api_error(500,"Failed to execute SQL query");
  397. return $sth;
  398. }