From 29e8264907cf69861ea2967b8b0dc4c641839ca4 Mon Sep 17 00:00:00 2001 From: syuilo Date: Fri, 10 Aug 2018 14:33:34 +0900 Subject: [PATCH] =?UTF-8?q?=E8=89=AF=E3=81=84=E6=84=9F=E3=81=98=E3=81=AB?= =?UTF-8?q?=E3=81=97=E3=81=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/models/drive-file.ts | 2 +- src/services/drive/add-file.ts | 39 +++++++++++++++++++++++++--------- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/src/models/drive-file.ts b/src/models/drive-file.ts index 33c045190..ad5496d7c 100644 --- a/src/models/drive-file.ts +++ b/src/models/drive-file.ts @@ -10,7 +10,7 @@ import DriveFileThumbnail, { deleteDriveFileThumbnail } from './drive-file-thumb const DriveFile = monkDb.get('driveFiles.files'); DriveFile.createIndex('md5'); -DriveFile.createIndex('metadata.uri', { sparse: true, unique: true }); +DriveFile.createIndex(['metadata.uri', 'metadata.userId'], { sparse: true, unique: true }); export default DriveFile; export const DriveFileChunk = monkDb.get('driveFiles.chunks'); diff --git a/src/services/drive/add-file.ts b/src/services/drive/add-file.ts index a04bab9db..701d54777 100644 --- a/src/services/drive/add-file.ts +++ b/src/services/drive/add-file.ts @@ -294,16 +294,35 @@ export default async function( metadata.uri = uri; } - const driveFile = isLink - ? await DriveFile.insert({ - length: 0, - uploadDate: new Date(), - md5: hash, - filename: detectedName, - metadata: metadata, - contentType: mime - }) - : await (save(fs.createReadStream(path), detectedName, mime, hash, size, metadata)); + let driveFile: IDriveFile; + + if (isLink) { + try { + driveFile = await DriveFile.insert({ + length: 0, + uploadDate: new Date(), + md5: hash, + filename: detectedName, + metadata: metadata, + contentType: mime + }); + } catch (e) { + // duplicate key error (when already registered) + if (e.code === 11000) { + log(`already registered ${metadata.uri}`); + + driveFile = await DriveFile.findOne({ + 'metadata.uri': metadata.uri, + 'metadata.userId': user._id + }); + } else { + console.error(e); + throw e; + } + } + } else { + driveFile = await (save(fs.createReadStream(path), detectedName, mime, hash, size, metadata)); + } log(`drive file has been created ${driveFile._id}`);