afs: Replace DATABASE_DIR by a runtime config option.
[paraslash.git] / aft.c
1 #include "para.h"
2 #include "error.h"
3 #include <sys/mman.h>
4 #include <fnmatch.h>
5 #include "afh.h"
6 #include "afs.h"
7 #include "net.h"
8 #include "string.h"
9 #include "vss.h"
10
11 #define AFS_AUDIO_FILE_DIR "/home/mp3"
12
13 static struct osl_table *audio_file_table;
14
15 /**
16 * Describes the layout of the mmapped-afs info struct.
17 *
18 * \sa struct afs_info.
19 */
20 enum afsi_offsets {
21 /** Where .last_played is stored. */
22 AFSI_LAST_PLAYED_OFFSET = 0,
23 /** Storage position of the attributes bitmap. */
24 AFSI_ATTRIBUTES_OFFSET = 8,
25 /** Storage position of the .num_played field. */
26 AFSI_NUM_PLAYED_OFFSET = 16,
27 /** Storage position of the .image_id field. */
28 AFSI_IMAGE_ID_OFFSET = 20,
29 /** Storage position of the .lyrics_id field. */
30 AFSI_LYRICS_ID_OFFSET = 24,
31 /** Storage position of the .audio_format_id field. */
32 AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
33 /** On-disk storage space needed. */
34 AFSI_SIZE = 29
35 };
36
37 /**
38 * Convert a struct afs_info to an osl object.
39 *
40 * \param afsi Pointer to the audio file info to be converted.
41 * \param obj Result pointer.
42 *
43 * \sa load_afsi().
44 */
45 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
46 {
47 char *buf = obj->data;
48
49 write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
50 write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
51 write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
52 write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
53 write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
54 write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
55 afsi->audio_format_id);
56 }
57
58 /**
59 * Get the audio file selector info struct stored in an osl object.
60 *
61 * \param afsi Points to the audio_file info structure to be filled in.
62 * \param obj The osl object holding the data.
63 *
64 * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
65 *
66 * \sa save_afsi().
67 */
68 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
69 {
70 char *buf = obj->data;
71 if (obj->size < AFSI_SIZE)
72 return -E_BAD_AFS;
73 afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
74 afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
75 afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
76 afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
77 afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
78 afsi->audio_format_id = read_u8(buf +
79 AFSI_AUDIO_FORMAT_ID_OFFSET);
80 return 1;
81 }
82
83 /** The columns of the audio file table. */
84 enum audio_file_table_columns {
85 /** The hash on the content of the audio file. */
86 AFTCOL_HASH,
87 /** The full path in the filesystem. */
88 AFTCOL_PATH,
89 /** The audio file selector info. */
90 AFTCOL_AFSI,
91 /** The audio format handler info. */
92 AFTCOL_AFHI,
93 /** The chunk table info and the chunk table of the audio file. */
94 AFTCOL_CHUNKS,
95 /** The number of columns of this table. */
96 NUM_AFT_COLUMNS
97 };
98
99 static struct osl_column_description aft_cols[] = {
100 [AFTCOL_HASH] = {
101 .storage_type = OSL_MAPPED_STORAGE,
102 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
103 .name = "hash",
104 .compare_function = osl_hash_compare,
105 .data_size = HASH_SIZE
106 },
107 [AFTCOL_PATH] = {
108 .storage_type = OSL_MAPPED_STORAGE,
109 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
110 .name = "path",
111 .compare_function = string_compare,
112 },
113 [AFTCOL_AFSI] = {
114 .storage_type = OSL_MAPPED_STORAGE,
115 .storage_flags = OSL_FIXED_SIZE,
116 .name = "afs_info",
117 .data_size = AFSI_SIZE
118 },
119 [AFTCOL_AFHI] = {
120 .storage_type = OSL_MAPPED_STORAGE,
121 .name = "afh_info",
122 },
123 [AFTCOL_CHUNKS] = {
124 .storage_type = OSL_DISK_STORAGE,
125 .name = "chunks",
126 }
127 };
128
129 static struct osl_table_description audio_file_table_desc = {
130 .name = "audio_files",
131 .num_columns = NUM_AFT_COLUMNS,
132 .flags = OSL_LARGE_TABLE,
133 .column_descriptions = aft_cols
134 };
135
136 static char *prefix_path(const char *prefix, int len, const char *path)
137 {
138 int speclen;
139 char *n;
140
141 for (;;) {
142 char c;
143 if (*path != '.')
144 break;
145 c = path[1];
146 /* "." */
147 if (!c) {
148 path++;
149 break;
150 }
151 /* "./" */
152 if (c == '/') {
153 path += 2;
154 continue;
155 }
156 if (c != '.')
157 break;
158 c = path[2];
159 if (!c)
160 path += 2;
161 else if (c == '/')
162 path += 3;
163 else
164 break;
165 /* ".." and "../" */
166 /* Remove last component of the prefix */
167 do {
168 if (!len)
169 return NULL;
170 len--;
171 } while (len && prefix[len-1] != '/');
172 continue;
173 }
174 if (!len)
175 return para_strdup(path);
176 speclen = strlen(path);
177 n = para_malloc(speclen + len + 1);
178 memcpy(n, prefix, len);
179 memcpy(n + len, path, speclen+1);
180 return n;
181 }
182
183 /*
184 * We fundamentally don't like some paths: we don't want
185 * dot or dot-dot anywhere.
186 *
187 * Also, we don't want double slashes or slashes at the
188 * end that can make pathnames ambiguous.
189 */
190 static int verify_dotfile(const char *rest)
191 {
192 /*
193 * The first character was '.', but that has already been discarded, we
194 * now test the rest.
195 */
196 switch (*rest) {
197 /* "." is not allowed */
198 case '\0': case '/':
199 return 1;
200
201 case '.':
202 if (rest[1] == '\0' || rest[1] == '/')
203 return -1;
204 }
205 return 1;
206 }
207
208 static int verify_path(const char *path, char **resolved_path)
209 {
210 const char *orig_path = path;
211 char c;
212 const char prefix[] = AFS_AUDIO_FILE_DIR "/";
213 const size_t prefix_len = strlen(prefix);
214
215 PARA_DEBUG_LOG("path: %s\n", path);
216 c = *path++;
217 if (!c)
218 return -E_BAD_PATH;
219 while (c) {
220 if (c == '/') {
221 c = *path++;
222 switch (c) {
223 default:
224 continue;
225 case '/': case '\0':
226 break;
227 case '.':
228 if (verify_dotfile(path) > 0)
229 continue;
230 }
231 *resolved_path = NULL;
232 return -E_BAD_PATH;
233 }
234 c = *path++;
235 }
236 if (*orig_path == '/')
237 *resolved_path = prefix_path("", 0, orig_path);
238 else
239 *resolved_path = prefix_path(prefix, prefix_len, orig_path);
240 PARA_DEBUG_LOG("resolved: %s\n", *resolved_path);
241 return *resolved_path? 1: -E_BAD_PATH;
242 }
243
244 enum afhi_offsets {
245 AFHI_SECONDS_TOTAL_OFFSET = 0,
246 AFHI_BITRATE_OFFSET = 4,
247 AFHI_FREQUENCY_OFFSET = 8,
248 AFHI_CHANNELS_OFFSET = 12,
249 AFHI_INFO_STRING_OFFSET = 13,
250 MIN_AFHI_SIZE = 14
251 };
252
253 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
254 {
255 if (!afhi)
256 return 0;
257 return strlen(afhi->info_string) + MIN_AFHI_SIZE;
258 }
259
260 static void save_afhi(struct audio_format_info *afhi, char *buf)
261 {
262 if (!afhi)
263 return;
264 write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
265 afhi->seconds_total);
266 write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
267 write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
268 write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
269 strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
270 PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
271 }
272
273 static void load_afhi(const char *buf, struct audio_format_info *afhi)
274 {
275 afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
276 afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
277 afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
278 afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
279 strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
280 }
281
282 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
283 {
284 if (!afhi)
285 return 0;
286 return 4 * afhi->chunks_total + 20;
287
288 }
289
290 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
291 enum chunk_info_offsets {
292 /** The total number of chunks (4 bytes). */
293 CHUNKS_TOTAL_OFFSET = 0,
294 /** The length of the audio file header (4 bytes). */
295 HEADER_LEN_OFFSET = 4,
296 /** The start of the audio file header (4 bytes). */
297 HEADER_OFFSET_OFFSET = 8,
298 /** The seconds part of the chunk time (4 bytes). */
299 CHUNK_TV_TV_SEC_OFFSET = 12,
300 /** The microseconds part of the chunk time (4 bytes). */
301 CHUNK_TV_TV_USEC = 16,
302 /** Chunk table entries start here. */
303 CHUNK_TABLE_OFFSET = 20,
304 };
305
306 /* TODO: audio format handlers could just produce this */
307 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
308 {
309 int i;
310
311 if (!afhi)
312 return;
313 write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
314 write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
315 write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
316 write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
317 write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
318 for (i = 0; i < afhi->chunks_total; i++)
319 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
320 }
321
322 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
323 {
324 char *buf = obj->data;
325 int i;
326
327 if (obj->size < CHUNK_TABLE_OFFSET)
328 return -E_BAD_DATA_SIZE;
329
330 afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
331 afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
332 afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
333 afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
334 afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
335
336 if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
337 return -E_BAD_DATA_SIZE;
338 afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
339 for (i = 0; i < afhi->chunks_total; i++)
340 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
341 return 1;
342 }
343
344 /**
345 * Get the row of the audio file table corresponding to the given path.
346 *
347 * \param path The full path of the audio file.
348 * \param row Result pointer.
349 *
350 * \return The return value of the underlying call to osl_get_row().
351 */
352 int aft_get_row_of_path(char *path, struct osl_row **row)
353 {
354 struct osl_object obj = {.data = path, .size = strlen(path) + 1};
355
356 PARA_NOTICE_LOG("audio_file_table: %p\n", audio_file_table);
357 return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
358 }
359
360 /**
361 * Get the row of the audio file table corresponding to the given hash value.
362 *
363 * \param hash The hash value of the desired audio file.
364 * \param row resul pointer.
365 *
366 * \return The return value of the underlying call to osl_get_row().
367 */
368 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
369 {
370 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
371 return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
372 }
373
374 /**
375 * Get the osl object holding the audio file selector info of a row.
376 *
377 * \param row Pointer to a row in the audio file table.
378 * \param obj Result pointer.
379 *
380 * \return The return value of the underlying call to osl_get_object().
381 */
382 int get_afsi_object_of_row(const void *row, struct osl_object *obj)
383 {
384 return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
385 }
386
387 /**
388 * Get the osl object holding the audio file selector info, given a path.
389 *
390 *
391 * \param path The full path of the audio file.
392 * \param obj Result pointer.
393 *
394 * \return Positive on success, negative on errors.
395 */
396 int get_afsi_object_of_path(char *path, struct osl_object *obj)
397 {
398 struct osl_row *row;
399 int ret = aft_get_row_of_path(path, &row);
400 if (ret < 0)
401 return ret;
402 return get_afsi_object_of_row(row, obj);
403 }
404
405 /**
406 * Get the audio file selector info, given a row of the audio file table.
407 *
408 * \param row Pointer to a row in the audio file table.
409 * \param afsi Result pointer.
410 *
411 * \return Positive on success, negative on errors.
412 */
413 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
414 {
415 struct osl_object obj;
416 int ret = get_afsi_object_of_row(row, &obj);
417 if (ret < 0)
418 return ret;
419 return load_afsi(afsi, &obj);
420 }
421
422 /**
423 * Get the path of an audio file, given a row of the audio file table.
424 *
425 * \param row Pointer to a row in the audio file table.
426 * \param path Result pointer.
427 *
428 * \return Positive on success, negative on errors.
429 */
430 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
431 {
432 struct osl_object path_obj;
433 int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
434 &path_obj);
435 if (ret < 0)
436 return ret;
437 *path = path_obj.data;
438 return 1;
439 }
440
441 /**
442 * Get the object containing the hash value of an audio file, given a row.
443 *
444 * \param row Pointer to a row of the audio file table.
445 * \param obj Result pointer.
446 *
447 * \return The return value of the underlying call to osl_get_object().
448 *
449 * \sa get_hash_of_row().
450 */
451 int get_hash_object_of_aft_row(const void *row, struct osl_object *obj)
452 {
453 return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
454 }
455
456 /**
457 * Get the hash value of an audio file, given a row of the audio file table.
458 *
459 * \param row Pointer to a row of the audio file table.
460 * \param hash Result pointer.
461 *
462 * \a hash points to mapped data and must not be freed by the caller.
463 *
464 * \return The return value of the underlying call to
465 * get_hash_object_of_aft_row().
466 */
467 static int get_hash_of_row(const void *row, HASH_TYPE **hash)
468 {
469 struct osl_object obj;
470 int ret = get_hash_object_of_aft_row(row, &obj);
471
472 if (ret < 0)
473 return ret;
474 *hash = obj.data;
475 return 1;
476 }
477
478 /**
479 * Get the audio format handler info, given a row of the audio file table.
480 *
481 * \param row Pointer to a row of the audio file table.
482 * \param afhi Result pointer.
483 *
484 * \return The return value of the underlying call to osl_get_object().
485 *
486 * \sa get_chunk_table_of_row().
487 */
488 int get_afhi_of_row(const void *row, struct audio_format_info *afhi)
489 {
490 struct osl_object obj;
491 int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
492 &obj);
493 if (ret < 0)
494 return ret;
495 load_afhi(obj.data, afhi);
496 return 1;
497 }
498
499 /**
500 * Get the chunk table of an audio file, given a row of the audio file table.
501 *
502 * \param row Pointer to a row of the audio file table.
503 * \param afhi Result pointer.
504 *
505 * \return The return value of the underlying call to osl_open_disk_object().
506 *
507 * \sa get_afhi_of_row().
508 */
509 int get_chunk_table_of_row(const void *row, struct audio_format_info *afhi)
510 {
511 struct osl_object obj;
512 int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
513 &obj);
514 if (ret < 0)
515 return ret;
516 ret = load_chunk_info(&obj, afhi);
517 osl_close_disk_object(&obj);
518 return ret;
519 }
520
521 /**
522 * Mmap the given audio file and update statistics.
523 *
524 * \param aft_row Determines the audio file to be opened and updated.
525 * \param afd Result pointer.
526 *
527 * On success, the numplayed field of the audio file selector info is increased
528 * and the lastplayed time is set to the current time. Finally, the score of
529 * the audio file is updated.
530 *
531 * \return Positive on success, negative on errors.
532 */
533 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
534 {
535 HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
536 struct osl_object afsi_obj;
537 struct afs_info new_afsi;
538 int ret = get_hash_of_row(aft_row, &aft_hash);
539
540 if (ret < 0)
541 return ret;
542 ret = get_audio_file_path_of_row(aft_row, &afd->path);
543 if (ret < 0)
544 return ret;
545 ret = get_afsi_object_of_row(aft_row, &afsi_obj);
546 if (ret < 0)
547 return ret;
548 ret = load_afsi(&afd->afsi, &afsi_obj);
549 if (ret < 0)
550 return ret;
551 ret = get_afhi_of_row(aft_row, &afd->afhi);
552 if (ret < 0)
553 return ret;
554 ret = get_chunk_table_of_row(aft_row, &afd->afhi);
555 if (ret < 0)
556 return ret;
557 ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
558 if (ret < 0)
559 goto err;
560 hash_function(afd->map.data, afd->map.size, file_hash);
561 ret = -E_HASH_MISMATCH;
562 if (hash_compare(file_hash, aft_hash))
563 goto err;
564 new_afsi = afd->afsi;
565 new_afsi.num_played++;
566 new_afsi.last_played = time(NULL);
567 save_afsi(&new_afsi, &afsi_obj); /* in-place update */
568 if (afd->current_play_mode == PLAY_MODE_PLAYLIST)
569 ret = playlist_update_audio_file(aft_row);
570 else
571 ret = mood_update_audio_file(aft_row, &afd->afsi);
572 return ret;
573 err:
574 free(afd->afhi.chunk_table);
575 return ret;
576 }
577
578 time_t now;
579
580 static int get_local_time(uint64_t *seconds, char *buf, size_t size)
581 {
582 struct tm t;
583
584 if (!localtime_r((time_t *)seconds, &t))
585 return -E_LOCALTIME;
586 if (*seconds + 6 * 30 * 24 * 3600 > now) {
587 if (!strftime(buf, size, "%b %e %k:%M", &t))
588 return -E_STRFTIME;
589 return 1;
590 }
591 if (!strftime(buf, size, "%b %e %Y", &t))
592 return -E_STRFTIME;
593 return 1;
594 }
595
596 #define GET_NUM_DIGITS(x, num) { \
597 typeof((x)) _tmp = PARA_ABS(x); \
598 *num = 1; \
599 if ((x)) \
600 while ((_tmp) > 9) { \
601 (_tmp) /= 10; \
602 (*num)++; \
603 } \
604 }
605
606 static short unsigned get_duration(int seconds_total, char *buf, short unsigned max_width)
607 {
608 short unsigned width;
609 int s = seconds_total;
610 unsigned hours = s / 3600, mins = (s % 3600) / 60, secs = s % 60;
611
612 if (s < 3600) { /* less than one hour => m:ss or mm:ss */
613 GET_NUM_DIGITS(mins, &width); /* 1 or 2 */
614 width += 3; /* 4 or 5 */
615 if (buf)
616 sprintf(buf, "%*u:%02u", max_width - width + 1, mins, secs);
617 return width;
618 }
619 /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
620 GET_NUM_DIGITS(hours, &width);
621 width += 6;
622 if (buf)
623 sprintf(buf, "%*u:%02u:%02u", max_width - width + 1, hours, mins, secs);
624 return width;
625 }
626
627 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
628 {
629 char *att_text, *att_line;
630
631 get_attribute_text(&afsi->attributes, " ", &att_text);
632 if (!att_text)
633 return para_strdup(att_bitmap);
634 att_line = make_message("%s (%s)", att_bitmap, att_text);
635 free(att_text);
636 return att_line;
637 }
638
639 static char *make_lyrics_line(struct afs_info *afsi)
640 {
641 char *lyrics_name;
642 lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
643 if (!lyrics_name)
644 return make_message("%u", afsi->lyrics_id);
645 return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
646 }
647
648 static char *make_image_line(struct afs_info *afsi)
649 {
650 char *image_name;
651 img_get_name_by_id(afsi->image_id, &image_name);
652 if (!image_name)
653 return make_message("%u", afsi->image_id);
654 return make_message("%u (%s)", afsi->image_id, image_name);
655 }
656
657 static int print_list_item(struct ls_data *d, struct ls_options *opts,
658 struct para_buffer *b)
659 {
660 int ret;
661 char att_buf[65];
662 char last_played_time[30];
663 char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
664 char score_buf[30] = "";
665 struct afs_info *afsi = &d->afsi;
666 struct audio_format_info *afhi = &d->afhi;
667 struct ls_widths *w = &opts->widths;
668 int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
669
670 if (opts->mode == LS_MODE_SHORT) {
671 para_printf(b, "%s\n", d->path);
672 return 1;
673 }
674 get_attribute_bitmap(&afsi->attributes, att_buf);
675 ret = get_local_time(&afsi->last_played, last_played_time,
676 sizeof(last_played_time));
677 if (ret < 0)
678 return ret;
679 get_duration(afhi->seconds_total, duration_buf, w->duration_width);
680 if (have_score) {
681 if (opts->mode == LS_MODE_LONG)
682 sprintf(score_buf, "%*li ", w->score_width, d->score);
683 else
684 sprintf(score_buf, "%li ", d->score);
685 }
686
687 if (opts->mode == LS_MODE_LONG) {
688 para_printf(b,
689 "%s" /* score */
690 "%s " /* attributes */
691 "%*d " /* image_id */
692 "%*d " /* lyrics_id */
693 "%*d " /* bitrate */
694 "%s " /* audio format */
695 "%*d " /* frequency */
696 "%d " /* channels */
697 "%s " /* duration */
698 "%*d " /* num_played */
699 "%s " /* last_played */
700 "%s\n", /* path */
701 score_buf,
702 att_buf,
703 w->image_id_width, afsi->image_id,
704 w->lyrics_id_width, afsi->lyrics_id,
705 w->bitrate_width, afhi->bitrate,
706 audio_format_name(afsi->audio_format_id),
707 w->frequency_width, afhi->frequency,
708 afhi->channels,
709 duration_buf,
710 w->num_played_width, afsi->num_played,
711 last_played_time,
712 d->path
713 );
714 return 1;
715 }
716 if (opts->mode == LS_MODE_VERBOSE) {
717 char asc_hash[2 * HASH_SIZE + 1];
718 char *att_line, *lyrics_line, *image_line;
719
720 hash_to_asc(d->hash, asc_hash);
721 att_line = make_attribute_line(att_buf, afsi);
722 lyrics_line = make_lyrics_line(afsi);
723 image_line = make_image_line(afsi);
724 para_printf(b,
725 "%s: %s\n" /* path */
726 "%s%s%s" /* score */
727 "attributes: %s\n"
728 "hash: %s\n"
729 "image_id: %s\n"
730 "lyrics_id: %s\n"
731 "bitrate: %dkbit/s\n"
732 "format: %s\n"
733 "frequency: %dHz\n"
734 "channels: %d\n"
735 "duration: %s\n"
736 "num_played: %d\n"
737 "last_played: %s\n\n",
738 (opts->flags & LS_FLAG_FULL_PATH)?
739 "path" : "file", d->path,
740 have_score? "score: " : "", score_buf,
741 have_score? "\n" : "",
742 att_line,
743 asc_hash,
744 image_line,
745 lyrics_line,
746 afhi->bitrate,
747 audio_format_name(afsi->audio_format_id),
748 afhi->frequency,
749 afhi->channels,
750 duration_buf,
751 afsi->num_played,
752 last_played_time
753 );
754 free(att_line);
755 free(lyrics_line);
756 free(image_line);
757 return 1;
758 }
759 return 1;
760 }
761
762 static int ls_audio_format_compare(const void *a, const void *b)
763 {
764 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
765 return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
766 }
767
768 static int ls_duration_compare(const void *a, const void *b)
769 {
770 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
771 return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
772 }
773
774 static int ls_bitrate_compare(const void *a, const void *b)
775 {
776 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
777 return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
778 }
779
780 static int ls_lyrics_id_compare(const void *a, const void *b)
781 {
782 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
783 return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
784 }
785
786 static int ls_image_id_compare(const void *a, const void *b)
787 {
788 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
789 return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
790 }
791
792 static int ls_channels_compare(const void *a, const void *b)
793 {
794 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
795 return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
796 }
797
798 static int ls_frequency_compare(const void *a, const void *b)
799 {
800 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
801 return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
802 }
803
804 static int ls_num_played_compare(const void *a, const void *b)
805 {
806 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
807 return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
808 }
809
810 static int ls_last_played_compare(const void *a, const void *b)
811 {
812 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
813 return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
814 }
815
816 static int ls_score_compare(const void *a, const void *b)
817 {
818 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
819 return NUM_COMPARE(d1->score, d2->score);
820 }
821
822 static int ls_path_compare(const void *a, const void *b)
823 {
824 struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
825 return strcmp(d1->path, d2->path);
826 }
827
828 static int sort_matching_paths(struct ls_options *options)
829 {
830 size_t nmemb = options->num_matching_paths;
831 size_t size = sizeof(uint32_t);
832 int (*compar)(const void *, const void *);
833 int i;
834
835 options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
836 for (i = 0; i < nmemb; i++)
837 options->data_ptr[i] = options->data + i;
838
839 /* In these cases the array is already sorted */
840 if (options->sorting == LS_SORT_BY_PATH
841 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
842 && (options->flags & LS_FLAG_FULL_PATH))
843 return 1;
844 if (options->sorting == LS_SORT_BY_SCORE &&
845 options->flags & LS_FLAG_ADMISSIBLE_ONLY)
846 return 1;
847
848 switch (options->sorting) {
849 case LS_SORT_BY_PATH:
850 compar = ls_path_compare; break;
851 case LS_SORT_BY_SCORE:
852 compar = ls_score_compare; break;
853 case LS_SORT_BY_LAST_PLAYED:
854 compar = ls_last_played_compare; break;
855 case LS_SORT_BY_NUM_PLAYED:
856 compar = ls_num_played_compare; break;
857 case LS_SORT_BY_FREQUENCY:
858 compar = ls_frequency_compare; break;
859 case LS_SORT_BY_CHANNELS:
860 compar = ls_channels_compare; break;
861 case LS_SORT_BY_IMAGE_ID:
862 compar = ls_image_id_compare; break;
863 case LS_SORT_BY_LYRICS_ID:
864 compar = ls_lyrics_id_compare; break;
865 case LS_SORT_BY_BITRATE:
866 compar = ls_bitrate_compare; break;
867 case LS_SORT_BY_DURATION:
868 compar = ls_duration_compare; break;
869 case LS_SORT_BY_AUDIO_FORMAT:
870 compar = ls_audio_format_compare; break;
871 default:
872 return -E_BAD_SORT;
873 }
874 qsort(options->data_ptr, nmemb, size, compar);
875 return 1;
876 }
877
878 /* row is either an aft_row or a row of the score table */
879 /* TODO: Only compute widths if we need them */
880 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
881 {
882 int ret, i;
883 struct ls_options *options = ls_opts;
884 struct ls_data *d;
885 struct ls_widths *w;
886 unsigned short num_digits;
887 unsigned tmp;
888 struct osl_row *aft_row;
889 long score;
890 char *path;
891
892 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
893 ret = get_score_and_aft_row(row, &score, &aft_row);
894 if (ret < 0)
895 return ret;
896 } else
897 aft_row = row;
898 ret = get_audio_file_path_of_row(aft_row, &path);
899 if (ret < 0)
900 return ret;
901 if (!(options->flags & LS_FLAG_FULL_PATH)) {
902 char *p = strrchr(path, '/');
903 if (p)
904 path = p + 1;
905 }
906 if (options->num_patterns) {
907 for (i = 0; i < options->num_patterns; i++) {
908 ret = fnmatch(options->patterns[i], path, FNM_PATHNAME);
909 if (!ret)
910 break;
911 if (ret == FNM_NOMATCH)
912 continue;
913 return -E_FNMATCH;
914 }
915 if (i >= options->num_patterns) /* no match */
916 return 1;
917 }
918 tmp = options->num_matching_paths++;
919 if (options->num_matching_paths > options->array_size) {
920 options->array_size++;
921 options->array_size *= 2;
922 options->data = para_realloc(options->data, options->array_size
923 * sizeof(*options->data));
924 }
925 d = options->data + tmp;
926 ret = get_afsi_of_row(aft_row, &d->afsi);
927 if (ret < 0)
928 return ret;
929 ret = get_afhi_of_row(aft_row, &d->afhi);
930 if (ret < 0)
931 return ret;
932 d->path = path;
933 ret = get_hash_of_row(aft_row, &d->hash);
934 if (ret < 0)
935 return ret;
936 w = &options->widths;
937 GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
938 w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
939 GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
940 w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
941 GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
942 w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
943 GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
944 w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
945 GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
946 w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
947 /* just get the number of chars to print this amount of time */
948 tmp = get_duration(d->afhi.seconds_total, NULL, 0);
949 w->duration_width = PARA_MAX(w->duration_width, tmp);
950 if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
951 GET_NUM_DIGITS(score, &num_digits);
952 num_digits++; /* add one for the sign (space or "-") */
953 w->score_width = PARA_MAX(w->score_width, num_digits);
954 d->score = score;
955 }
956 return 1;
957 }
958
959 static int com_ls_callback(const struct osl_object *query,
960 struct osl_object *ls_output)
961 {
962 struct ls_options *opts = query->data;
963 char *p, *pattern_start = (char *)query->data + sizeof(*opts);
964 struct para_buffer b = {.buf = NULL, .size = 0};
965 int i = 0, ret;
966
967 PARA_NOTICE_LOG("%d patterns\n", opts->num_patterns);
968 if (opts->num_patterns) {
969 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
970 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
971 opts->patterns[i] = p;
972 p += strlen(p) + 1;
973 PARA_NOTICE_LOG("pattern %d: %s\n", i, opts->patterns[i]);
974 }
975 } else
976 opts->patterns = NULL;
977 if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
978 ret = admissible_file_loop(opts, prepare_ls_row);
979 else
980 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
981 prepare_ls_row);
982 if (ret < 0)
983 goto out;
984 ret = opts->num_patterns? -E_NO_MATCH : 1;
985 if (!opts->num_matching_paths) {
986 PARA_NOTICE_LOG("no match, ret: %d\n", ret);
987 goto out;
988 }
989 ret = sort_matching_paths(opts);
990 if (ret < 0)
991 goto out;
992 if (opts->flags & LS_FLAG_REVERSE)
993 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
994 ret = print_list_item(opts->data_ptr[i], opts, &b);
995 if (ret < 0)
996 break;
997 }
998 else
999 for (i = 0; i < opts->num_matching_paths; i++) {
1000 ret = print_list_item(opts->data_ptr[i], opts, &b);
1001 if (ret < 0)
1002 break;
1003 }
1004 ret = 1;
1005 out:
1006 ls_output->data = b.buf;
1007 ls_output->size = b.size;
1008 free(opts->data);
1009 free(opts->data_ptr);
1010 free(opts->patterns);
1011 return ret;
1012 }
1013
1014 /*
1015 * TODO: flags -h (sort by hash)
1016 *
1017 * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1018 * full list: list everything, including afsi, afhi, atts as clear text
1019 *
1020 * */
1021 int com_afs_ls(int fd, int argc, char * const * const argv)
1022 {
1023 int i, ret;
1024 unsigned flags = 0;
1025 enum ls_sorting_method sort = LS_SORT_BY_PATH;
1026 enum ls_listing_mode mode = LS_MODE_SHORT;
1027 struct ls_options opts = {.patterns = NULL};
1028 struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1029 ls_output;
1030
1031 for (i = 1; i < argc; i++) {
1032 const char *arg = argv[i];
1033 if (arg[0] != '-')
1034 break;
1035 if (!strcmp(arg, "--")) {
1036 i++;
1037 break;
1038 }
1039 if (!strncmp(arg, "-l", 2)) {
1040 if (!*(arg + 2)) {
1041 mode = LS_MODE_LONG;
1042 continue;
1043 }
1044 if (*(arg + 3))
1045 return -E_AFT_SYNTAX;
1046 switch(*(arg + 2)) {
1047 case 's':
1048 mode = LS_MODE_SHORT;
1049 continue;
1050 case 'l':
1051 mode = LS_MODE_LONG;
1052 continue;
1053 case 'v':
1054 mode = LS_MODE_VERBOSE;
1055 continue;
1056 case 'm':
1057 mode = LS_MODE_MBOX;
1058 continue;
1059 default:
1060 return -E_AFT_SYNTAX;
1061 }
1062 }
1063 if (!strcmp(arg, "-p")) {
1064 flags |= LS_FLAG_FULL_PATH;
1065 continue;
1066 }
1067 if (!strcmp(arg, "-a")) {
1068 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1069 continue;
1070 }
1071 if (!strcmp(arg, "-r")) {
1072 flags |= LS_FLAG_REVERSE;
1073 continue;
1074 }
1075 if (!strncmp(arg, "-s", 2)) {
1076 if (!*(arg + 2) || *(arg + 3))
1077 return -E_AFT_SYNTAX;
1078 switch(*(arg + 2)) {
1079 case 'p':
1080 sort = LS_SORT_BY_PATH;
1081 continue;
1082 case 's': /* -ss implies -a */
1083 sort = LS_SORT_BY_SCORE;
1084 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1085 continue;
1086 case 'l':
1087 sort = LS_SORT_BY_LAST_PLAYED;
1088 continue;
1089 case 'n':
1090 sort = LS_SORT_BY_NUM_PLAYED;
1091 continue;
1092 case 'f':
1093 sort = LS_SORT_BY_FREQUENCY;
1094 continue;
1095 case 'c':
1096 sort = LS_SORT_BY_CHANNELS;
1097 continue;
1098 case 'i':
1099 sort = LS_SORT_BY_IMAGE_ID;
1100 continue;
1101 case 'y':
1102 sort = LS_SORT_BY_LYRICS_ID;
1103 continue;
1104 case 'b':
1105 sort = LS_SORT_BY_BITRATE;
1106 continue;
1107 case 'd':
1108 sort = LS_SORT_BY_DURATION;
1109 continue;
1110 case 'a':
1111 sort = LS_SORT_BY_AUDIO_FORMAT;
1112 continue;
1113 default:
1114 return -E_AFT_SYNTAX;
1115 }
1116 }
1117 return -E_AFT_SYNTAX;
1118 }
1119 time(&now);
1120 opts.flags = flags;
1121 opts.sorting = sort;
1122 opts.mode = mode;
1123 opts.num_patterns = argc - i;
1124 ret = send_option_arg_callback_request(&query, opts.num_patterns,
1125 argv + i, com_ls_callback, &ls_output);
1126 if (ret >= 0 && ls_output.data) {
1127 send_buffer(fd, (char *)ls_output.data);
1128 free(ls_output.data);
1129 }
1130 return ret;
1131 }
1132
1133 /**
1134 * Call the given function for each file in the audio file table.
1135 *
1136 * \param private_data An arbitrary data pointer, passed to \a func.
1137 * \param func The custom function to be called.
1138 *
1139 * \return The return value of the underlying call to osl_rbtree_loop().
1140 */
1141 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1142 {
1143 return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1144 func);
1145 }
1146
1147 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1148 {
1149 const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1150 struct osl_row *row;
1151
1152 osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1153 return row;
1154 }
1155
1156 enum aft_row_offsets {
1157 AFTROW_AFHI_OFFSET_POS = 0,
1158 AFTROW_CHUNKS_OFFSET_POS = 2,
1159 AFTROW_AUDIO_FORMAT_OFFSET = 4,
1160 AFTROW_FLAGS_OFFSET = 5,
1161 AFTROW_HASH_OFFSET = 9,
1162 AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1163 };
1164
1165 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1166 * In this case, afhi won't be stored in the buffer */
1167 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1168 struct audio_format_info *afhi, uint32_t flags,
1169 uint8_t audio_format_num, struct osl_object *obj)
1170 {
1171 size_t path_len = strlen(path) + 1;
1172 size_t afhi_size = sizeof_afhi_buf(afhi);
1173 size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1174 + sizeof_chunk_info_buf(afhi);
1175 char *buf = para_malloc(size);
1176 uint16_t pos;
1177
1178 write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1179 write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1180
1181 memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1182 strcpy(buf + AFTROW_PATH_OFFSET, path);
1183
1184 pos = AFTROW_PATH_OFFSET + path_len;
1185 PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1186 PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1187 pos + afhi_size - 1);
1188 write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1189 save_afhi(afhi, buf + pos);
1190
1191 pos += afhi_size;
1192 PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1193 write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1194 save_chunk_info(afhi, buf + pos);
1195 PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1196 obj->data = buf;
1197 obj->size = size;
1198 }
1199
1200 /*
1201 input:
1202 ~~~~~~
1203 HS: hash sister
1204 PB: path brother
1205 F: force flag given
1206
1207 output:
1208 ~~~~~~~
1209 AFHI: whether afhi and chunk table are computed and sent
1210 ACTION: table modifications to be performed
1211
1212 +---+----+-----+------+---------------------------------------------------+
1213 | HS | PB | F | AFHI | ACTION
1214 +---+----+-----+------+---------------------------------------------------+
1215 | Y | Y | Y | Y | if HS != PB: remove PB. HS: force afhi update,
1216 | | update path, keep afsi
1217 +---+----+-----+------+---------------------------------------------------+
1218 | Y | Y | N | N | if HS == PB: do not send callback request at all.
1219 | | otherwise: remove PB, HS: update path, keep afhi,
1220 | | afsi.
1221 +---+----+-----+------+---------------------------------------------------+
1222 | Y | N | Y | Y | (rename) force afhi update of HS, update path of
1223 | | HS, keep afsi
1224 +---+----+-----+------+---------------------------------------------------+
1225 | Y | N | N | N | (file rename) update path of HS, keep afsi, afhi
1226 +---+----+-----+------+---------------------------------------------------+
1227 | N | Y | Y | Y | (file change) update afhi, hash, of PB, keep afsi
1228 | | (force has no effect)
1229 +---+----+-----+------+---------------------------------------------------+
1230 | N | Y | N | Y | (file change) update afhi, hash of PB, keep afsi
1231 +---+----+-----+------+---------------------------------------------------+
1232 | N | N | Y | Y | (new file) create new entry (force has no effect)
1233 +---+----+-----+------+---------------------------------------------------+
1234 | N | N | N | Y | (new file) create new entry
1235 +---+----+-----+------+---------------------------------------------------+
1236
1237 afhi <=> force or no HS
1238
1239 */
1240
1241
1242 #define ADD_FLAG_LAZY 1
1243 #define ADD_FLAG_FORCE 2
1244 #define ADD_FLAG_VERBOSE 4
1245
1246 /* TODO: change log messages so that they get written to the result buffer */
1247
1248 static int com_add_callback(const struct osl_object *query,
1249 __a_unused struct osl_object *result)
1250 {
1251 char *buf = query->data, *path;
1252 struct osl_row *pb, *aft_row;
1253 const struct osl_row *hs;
1254 struct osl_object objs[NUM_AFT_COLUMNS];
1255 HASH_TYPE *hash;
1256 char asc[2 * HASH_SIZE + 1];
1257 int ret;
1258 char afsi_buf[AFSI_SIZE];
1259 uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1260 struct afs_info default_afsi = {.last_played = 0};
1261
1262 hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1263 hash_to_asc(hash, asc);;
1264 objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1265 objs[AFTCOL_HASH].size = HASH_SIZE;
1266
1267 path = buf + AFTROW_PATH_OFFSET;
1268 objs[AFTCOL_PATH].data = path;
1269 objs[AFTCOL_PATH].size = strlen(path) + 1;
1270
1271 PARA_DEBUG_LOG("request to add %s with hash %s\n", path, asc);
1272 hs = find_hash_sister(hash);
1273 ret = aft_get_row_of_path(path, &pb);
1274 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1275 return ret;
1276 if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1277 if (flags & ADD_FLAG_VERBOSE)
1278 PARA_NOTICE_LOG("ignoring duplicate %p\n", path);
1279 return 1;
1280 }
1281 if (hs && hs != pb) {
1282 struct osl_object obj;
1283 if (pb) { /* hs trumps pb, remove pb */
1284 if (flags & ADD_FLAG_VERBOSE)
1285 PARA_NOTICE_LOG("removing path brother\n");
1286 ret = osl_del_row(audio_file_table, pb);
1287 if (ret < 0)
1288 return ret;
1289 pb = NULL;
1290 }
1291 /* file rename, update hs' path */
1292 ret = osl_get_object(audio_file_table, hs, AFTCOL_PATH, &obj);
1293 if (flags & ADD_FLAG_VERBOSE)
1294 PARA_NOTICE_LOG("rename %s -> %s\n", (char *)obj.data, path);
1295 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1296 &objs[AFTCOL_PATH]);
1297 if (ret < 0)
1298 return ret;
1299 if (!(flags & ADD_FLAG_FORCE))
1300 return ret;
1301 }
1302 /* no hs or force mode, child must have sent afhi */
1303 uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1304 uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1305
1306 objs[AFTCOL_AFHI].data = buf + afhi_offset;
1307 objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1308 if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1309 return -E_NO_AFHI;
1310 objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1311 objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1312 if (pb && !hs) { /* update pb's hash */
1313 char old_asc[2 * HASH_SIZE + 1];
1314 HASH_TYPE *old_hash;
1315 ret = get_hash_of_row(pb, &old_hash);
1316 if (ret < 0)
1317 return ret;
1318 hash_to_asc(old_hash, old_asc);
1319 if (flags & ADD_FLAG_VERBOSE)
1320 PARA_NOTICE_LOG("file change: %s %s -> %s\n", path,
1321 old_asc, asc);
1322 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1323 &objs[AFTCOL_HASH]);
1324 if (ret < 0)
1325 return ret;
1326 }
1327 if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1328 const void *row = pb? pb : hs;
1329 /* update afhi and chunk_table */
1330 if (flags & ADD_FLAG_VERBOSE)
1331 PARA_NOTICE_LOG("updating audio format handler info (%zd bytes)\n",
1332 objs[AFTCOL_AFHI].size);
1333 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1334 &objs[AFTCOL_AFHI]);
1335 if (ret < 0)
1336 return ret;
1337 if (flags & ADD_FLAG_VERBOSE)
1338 PARA_NOTICE_LOG("updating chunk table\n");
1339 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1340 &objs[AFTCOL_CHUNKS]);
1341 if (ret < 0)
1342 return ret;
1343 ret = mood_update_audio_file(row, NULL);
1344 if (ret < 0)
1345 return ret;
1346 }
1347 /* new entry, use default afsi */
1348 default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1349 default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1350
1351 if (flags & ADD_FLAG_VERBOSE)
1352 PARA_NOTICE_LOG("adding %s\n", path);
1353 objs[AFTCOL_AFSI].data = &afsi_buf;
1354 objs[AFTCOL_AFSI].size = AFSI_SIZE;
1355 save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1356 ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1357 if (ret < 0)
1358 return ret;
1359 return mood_update_audio_file(aft_row, NULL);
1360 }
1361
1362 struct private_add_data {
1363 int fd;
1364 uint32_t flags;
1365 };
1366
1367 static int path_brother_callback(const struct osl_object *query,
1368 struct osl_object *result)
1369 {
1370 char *path = query->data;
1371 struct osl_row *path_brother;
1372 int ret = aft_get_row_of_path(path, &path_brother);
1373 if (ret < 0)
1374 return ret;
1375 result->data = para_malloc(sizeof(path_brother));
1376 result->size = sizeof(path_brother);
1377 *(struct osl_row **)(result->data) = path_brother;
1378 return 1;
1379 }
1380
1381 static int hash_sister_callback(const struct osl_object *query,
1382 struct osl_object *result)
1383 {
1384 HASH_TYPE *hash = query->data;
1385 struct osl_row *hash_sister;
1386
1387 hash_sister = find_hash_sister(hash);
1388 if (!hash_sister)
1389 return -E_RB_KEY_NOT_FOUND;
1390 result->data = para_malloc(sizeof(hash_sister));
1391 result->size = sizeof(hash_sister);
1392 *(struct osl_row **)(result->data) = hash_sister;
1393 return 1;
1394 }
1395
1396
1397 static int add_one_audio_file(const char *arg, const void *private_data)
1398 {
1399 int ret;
1400 uint8_t format_num = -1;
1401 const struct private_add_data *pad = private_data;
1402 struct audio_format_info afhi, *afhi_ptr = NULL;
1403 struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1404 struct osl_object map, obj, query, result;
1405 char *path;
1406 HASH_TYPE hash[HASH_SIZE];
1407
1408 afhi.header_offset = 0;
1409 afhi.header_len = 0;
1410 ret = verify_path(arg, &path);
1411 if (ret < 0)
1412 return ret;
1413 query.data = path;
1414 query.size = strlen(path) + 1;
1415 ret = send_callback_request(path_brother_callback, &query, &result);
1416 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1417 goto out_free;
1418 if (ret >= 0) {
1419 pb = *(struct osl_row **)result.data;
1420 free(result.data);
1421 }
1422 ret = 1;
1423 if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1424 if (pad->flags & ADD_FLAG_VERBOSE)
1425 ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1426 goto out_free;
1427 }
1428 /* We still want to add this file. Compute its hash. */
1429 ret = mmap_full_file(path, O_RDONLY, &map);
1430 if (ret < 0)
1431 goto out_free;
1432 hash_function(map.data, map.size, hash);
1433
1434 /* Check whether database contains file with the same hash. */
1435 query.data = hash;
1436 query.size = HASH_SIZE;
1437 ret = send_callback_request(hash_sister_callback, &query, &result);
1438 if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1439 goto out_free;
1440 if (ret >= 0) {
1441 hs = *(struct osl_row **)result.data;
1442 free(result.data);
1443 }
1444 /* Return success if we already know this file. */
1445 ret = 1;
1446 if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1447 if (pad->flags & ADD_FLAG_VERBOSE)
1448 ret = send_va_buffer(pad->fd,
1449 "not forcing update: %s\n", path);
1450 goto out_unmap;
1451 }
1452 /*
1453 * we won't recalculate the audio format info and the chunk table if
1454 * there is a hash sister unless in FORCE mode.
1455 */
1456 if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1457 ret = compute_afhi(path, map.data, map.size, &afhi);
1458 if (ret < 0) {
1459 ret = send_va_buffer(pad->fd,
1460 "audio format of %s not recognized\n", path);
1461 goto out_unmap;
1462 }
1463 format_num = ret;
1464 afhi_ptr = &afhi;
1465 }
1466 munmap(map.data, map.size);
1467 save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1468 /* Ask afs to consider this entry for adding. */
1469 ret = send_callback_request(com_add_callback, &obj, NULL);
1470 goto out_free;
1471
1472 out_unmap:
1473 munmap(map.data, map.size);
1474 out_free:
1475 free(obj.data);
1476 free(path);
1477 if (afhi_ptr)
1478 free(afhi_ptr->chunk_table);
1479 return ret;
1480 }
1481
1482 int com_add(int fd, int argc, char * const * const argv)
1483 {
1484 int i, ret;
1485 struct private_add_data pad = {.fd = fd, .flags = 0};
1486 struct stat statbuf;
1487
1488 PARA_NOTICE_LOG("argv[1]: %s\n", argv[1]);
1489 for (i = 1; i < argc; i++) {
1490 const char *arg = argv[i];
1491 if (arg[0] != '-')
1492 break;
1493 if (!strcmp(arg, "--")) {
1494 i++;
1495 break;
1496 }
1497 if (!strcmp(arg, "-l")) {
1498 pad.flags |= ADD_FLAG_LAZY;
1499 continue;
1500 }
1501 if (!strcmp(arg, "-f")) {
1502 pad.flags |= ADD_FLAG_FORCE;
1503 continue;
1504 }
1505 if (!strcmp(arg, "-v")) {
1506 pad.flags |= ADD_FLAG_VERBOSE;
1507 continue;
1508 }
1509 }
1510 if (argc <= i)
1511 return -E_AFT_SYNTAX;
1512 for (; i < argc; i++) {
1513 ret = stat(argv[i], &statbuf);
1514 if (ret < 0)
1515 return -E_AFS_STAT;
1516 if (S_ISDIR(statbuf.st_mode)) {
1517 ret = for_each_file_in_dir(argv[i],
1518 add_one_audio_file, &pad);
1519 if (ret < 0)
1520 return ret;
1521 continue;
1522 }
1523 ret = add_one_audio_file(argv[i], &pad);
1524 if (ret < 0)
1525 goto out;
1526 }
1527 ret = 1;
1528 out:
1529 return ret;
1530
1531 }
1532
1533 struct com_touch_options {
1534 long num_played;
1535 long last_played;
1536 long lyrics_id;
1537 long image_id;
1538 };
1539
1540 static int com_touch_callback(const struct osl_object *query,
1541 __a_unused struct osl_object *result)
1542 {
1543 struct com_touch_options *cto = query->data;
1544 char *p = (char *)query->data + sizeof(*cto);
1545 size_t len;
1546 int ret, no_options = cto->num_played < 0 && cto->last_played < 0 &&
1547 cto->lyrics_id < 0 && cto->image_id < 0;
1548
1549 for (;p < (char *)query->data + query->size; p += len + 1) {
1550 struct afs_info old_afsi, new_afsi;
1551 struct osl_object obj;
1552 struct osl_row *row;
1553
1554 len = strlen(p);
1555 ret = aft_get_row_of_path(p, &row);
1556 if (ret < 0)
1557 return ret;
1558 ret = get_afsi_object_of_row(row, &obj);
1559 if (ret < 0)
1560 return ret;
1561 ret = load_afsi(&old_afsi, &obj);
1562 if (ret < 0)
1563 return ret;
1564 new_afsi = old_afsi;
1565 if (no_options) {
1566 new_afsi.num_played++;
1567 new_afsi.last_played = time(NULL);
1568 } else {
1569 if (cto->lyrics_id >= 0)
1570 new_afsi.lyrics_id = cto->lyrics_id;
1571 if (cto->image_id >= 0)
1572 new_afsi.image_id = cto->image_id;
1573 if (cto->num_played >= 0)
1574 new_afsi.num_played = cto->num_played;
1575 if (cto->last_played >= 0)
1576 new_afsi.last_played = cto->last_played;
1577 }
1578 save_afsi(&new_afsi, &obj); /* in-place update */
1579 ret = mood_update_audio_file(row, &old_afsi);
1580 if (ret < 0)
1581 return ret;
1582 }
1583 return 1;
1584 }
1585
1586 int com_touch(__a_unused int fd, int argc, char * const * const argv)
1587 {
1588 struct com_touch_options cto = {
1589 .num_played = -1,
1590 .last_played = -1,
1591 .lyrics_id = -1,
1592 .image_id = -1
1593 };
1594 struct osl_object options = {.data = &cto, .size = sizeof(cto)};
1595 int i, ret;
1596
1597
1598 for (i = 1; i < argc; i++) {
1599 const char *arg = argv[i];
1600 if (arg[0] != '-')
1601 break;
1602 if (!strcmp(arg, "--")) {
1603 i++;
1604 break;
1605 }
1606 if (!strncmp(arg, "-n", 2)) {
1607 ret = para_atol(arg + 2, &cto.num_played);
1608 if (ret < 0)
1609 goto err;
1610 continue;
1611 }
1612 if (!strncmp(arg, "-l", 2)) {
1613 ret = para_atol(arg + 2, &cto.last_played);
1614 if (ret < 0)
1615 goto err;
1616 continue;
1617 }
1618 if (!strncmp(arg, "-y", 2)) {
1619 ret = para_atol(arg + 2, &cto.lyrics_id);
1620 if (ret < 0)
1621 goto err;
1622 continue;
1623 }
1624 if (!strncmp(arg, "-i", 2)) {
1625 ret = para_atol(arg + 2, &cto.image_id);
1626 if (ret < 0)
1627 goto err;
1628 continue;
1629 }
1630 }
1631 ret = -E_AFT_SYNTAX;
1632 if (i >= argc)
1633 goto err;
1634 return send_option_arg_callback_request(&options, argc - i,
1635 argv + i, com_touch_callback, NULL);
1636 err:
1637 return ret;
1638 }
1639
1640 struct com_rm_options {
1641 uint32_t flags;
1642 };
1643
1644 static int com_rm_callback(const struct osl_object *query,
1645 __a_unused struct osl_object *result)
1646 {
1647 struct com_rm_options *cro = query->data;
1648 char *p = (char *)query->data + sizeof(*cro);
1649 size_t len;
1650 int ret;
1651
1652 for (;p < (char *)query->data + query->size; p += len + 1) {
1653 struct osl_row *row;
1654
1655 len = strlen(p);
1656 ret = aft_get_row_of_path(p, &row);
1657 if (ret < 0)
1658 return ret;
1659 ret = mood_delete_audio_file(row);
1660 if (ret < 0)
1661 return ret;
1662 ret = osl_del_row(audio_file_table, row);
1663 if (ret < 0)
1664 return ret;
1665 }
1666 return 1;
1667 }
1668
1669 /*
1670 * TODO options: -v verbose, -f dont stop if file not found
1671 * -h remove by hash, use fnmatch
1672 *
1673 * */
1674
1675 int com_afs_rm(__a_unused int fd, int argc, char * const * const argv)
1676 {
1677 struct com_rm_options cro = {.flags = 0};
1678 struct osl_object options = {.data = &cro, .size = sizeof(cro)};
1679 int i, ret;
1680
1681 for (i = 1; i < argc; i++) {
1682 const char *arg = argv[i];
1683 if (arg[0] != '-')
1684 break;
1685 if (!strcmp(arg, "--")) {
1686 i++;
1687 break;
1688 }
1689 }
1690 ret = -E_AFT_SYNTAX;
1691 if (i >= argc)
1692 goto err;
1693 return send_option_arg_callback_request(&options, argc - i,
1694 argv + i, com_rm_callback, NULL);
1695 err:
1696 return ret;
1697 }
1698
1699 /**
1700 * Close the audio file table.
1701 *
1702 * \param flags Ususal flags that are passed to osl_close_table().
1703 *
1704 * \sa osl_close_table().
1705 */
1706 void aft_shutdown(enum osl_close_flags flags)
1707 {
1708 osl_close_table(audio_file_table, flags);
1709 }
1710
1711 /**
1712 * Open the audio file table.
1713 *
1714 * \param ti Gets initialized by this function.
1715 * \param db The database directory.
1716 *
1717 * \return Positive on success, negative on errors.
1718 *
1719 * \sa osl_open_table().
1720 */
1721 int aft_init(struct table_info *ti, const char *db)
1722 {
1723 int ret;
1724
1725 audio_file_table_desc.dir = db;
1726 ti->desc = &audio_file_table_desc;
1727 ret = osl_open_table(ti->desc, &ti->table);
1728 if (ret >= 0) {
1729 unsigned num;
1730 audio_file_table = ti->table;
1731 osl_get_num_rows(audio_file_table, &num);
1732 PARA_INFO_LOG("audio file table contains %d files\n", num);
1733 return ret;
1734 }
1735 PARA_INFO_LOG("failed to open audio file table\n");
1736 audio_file_table = NULL;
1737 return ret == -E_NOENT? 1 : ret;
1738 }