Skip to content

Commit

Permalink
watch for file change and update
Browse files Browse the repository at this point in the history
  • Loading branch information
mienaiyami committed Feb 27, 2023
1 parent e70dd23 commit e77e3a4
Show file tree
Hide file tree
Showing 11 changed files with 156 additions and 60 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@fortawesome/react-fontawesome": "^0.2.0",
"@reduxjs/toolkit": "^1.9.3",
"@vscode/sudo-prompt": "^9.3.1",
"chokidar": "^3.5.3",
"cross-zip": "^4.0.0",
"electron-dl": "^3.5.0",
"electron-fetch": "^1.9.1",
Expand Down
25 changes: 20 additions & 5 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import { setUnzipping } from "./store/unzipping";
import { setLoadingManga } from "./store/isLoadingManga";
import { setLoadingMangaPercent } from "./store/loadingMangaPercent";
import { setLinkInReader } from "./store/linkInReader";
import { updateLastHistoryPage } from "./store/history";
import { refreshHistory, updateLastHistoryPage } from "./store/history";
import { setReaderOpen } from "./store/isReaderOpen";
import { setMangaInReader } from "./store/mangaInReader";
import { addBookmark } from "./store/bookmarks";
import { refreshBookmark } from "./store/bookmarks";
import { setTheme } from "./store/themes";
import { bookmarksPath, historyPath } from "./MainImports";

// window.logger.log("New window opening...");

Expand All @@ -38,8 +39,7 @@ export const AppContext = createContext<IAppContext>(null!);
const App = (): ReactElement => {
const appSettings = useAppSelector((state) => state.appSettings);
const isReaderOpen = useAppSelector((state) => state.isReaderOpen);
const linkInReader = useAppSelector((state) => state.linkInReader);
const bookmarks = useAppSelector((state) => state.bookmarks);
const linkInReader = useAppSelector((store) => store.linkInReader);
const theme = useAppSelector((state) => state.theme.name);

const pageNumberInputRef: React.RefObject<HTMLInputElement> = createRef();
Expand Down Expand Up @@ -198,7 +198,8 @@ const App = (): ReactElement => {
// });
// };
const closeReader = () => {
dispatch(updateLastHistoryPage({ linkInReader: linkInReader.link }));
// console.log(linkInReader, window.app.linkInReader);
dispatch(updateLastHistoryPage());
dispatch(setReaderOpen(false));
dispatch(setLinkInReader({ link: "", page: 1 }));
dispatch(setLoadingManga(false));
Expand Down Expand Up @@ -250,6 +251,7 @@ const App = (): ReactElement => {
});
window.electron.ipcRenderer.on("recordPageNumber", () => {
if (isReaderOpen) closeReader();
else if (window.app.linkInReader.link !== "") dispatch(updateLastHistoryPage());
});
window.app.titleBarHeight = parseFloat(
window.getComputedStyle(document.body).getPropertyValue("--titleBar-height")
Expand All @@ -260,9 +262,22 @@ const App = (): ReactElement => {
window.location.reload();
}
};

// watching for file changes;
const watcher = window.chokidar.watch([historyPath, bookmarksPath]);
watcher.on("change", (path) => {
if (path === historyPath) dispatch(refreshHistory());
if (path === bookmarksPath) dispatch(refreshBookmark());
});

window.addEventListener("keydown", eventsOnStart);
return () => {
removeEventListener("keydown", eventsOnStart);
watcher.removeAllListeners();
window.electron.ipcRenderer.removeAllListeners("loadMangaFromLink");
window.electron.ipcRenderer.removeAllListeners("setWindowIndex");
window.electron.ipcRenderer.removeAllListeners("canCheckForUpdate");
window.electron.ipcRenderer.removeAllListeners("recordPageNumber");
};
}, []);

Expand Down
1 change: 1 addition & 0 deletions src/Components/Reader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,7 @@ const Reader = () => {
imgContRef.current?.scrollTo(0, scrollPosPercent * imgContRef.current.scrollHeight);
}, [appSettings.readerSettings.readerWidth, isSideListPinned]);
useEffect(() => {
window.app.linkInReader = linkInReader;
if (linkInReader && linkInReader.link !== "") {
if (mangaInReader && mangaInReader.link === linkInReader.link) return;
checkForImgsAndLoad(linkInReader);
Expand Down
7 changes: 5 additions & 2 deletions src/Components/ReaderSideList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,10 @@ const ReaderSideList = ({
tooltip="Open Previous"
disabled={prevNextChapter.prev === "~"}
clickAction={() => {
dispatch(updateLastHistoryPage({ linkInReader: linkInReader.link }));
// todo: removing updateHistory page on chapter change in same manga
// dispatch(updateLastHistoryPage({ linkInReader: linkInReader.link }));

// todo : do i need this?
dispatch(setLinkInReader({ link: prevNextChapter.prev, page: 1 }));
}}
>
Expand Down Expand Up @@ -370,7 +373,7 @@ const ReaderSideList = ({
tooltip="Open Next"
disabled={prevNextChapter.next === "~"}
clickAction={() => {
dispatch(updateLastHistoryPage({ linkInReader: linkInReader.link }));
// dispatch(updateLastHistoryPage({ linkInReader: linkInReader.link }));
dispatch(setLinkInReader({ link: prevNextChapter.next, page: 1 }));
}}
>
Expand Down
20 changes: 20 additions & 0 deletions src/MainImports.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { app, dialog, getCurrentWindow, clipboard, nativeImage, shell } from "@electron/remote";
import { ipcRenderer, webFrame } from "electron";
import crossZip from "cross-zip";
import chokidar from "chokidar";
import log from "electron-log";
log.transports.file.resolvePath = () => path.join(app.getPath("userData"), "logs/renderer.log");
/*//! i know its dangerous but its offline app and i was unable to get BrowserWindow to work
Expand Down Expand Up @@ -114,6 +115,10 @@ declare global {
* Library to un-archive zip or cbz.
*/
crossZip: typeof crossZip;
/**
* watch for change in file/dir.
*/
chokidar: typeof chokidar;
logger: typeof log;
/**
* Supported image formats.
Expand All @@ -138,6 +143,16 @@ declare global {
currentPageNumber: number;
scrollToPage: (pageNumber: number, behavior?: ScrollBehavior, callback?: () => void) => void;
keyRepeated: boolean;

// todo: fix
/**
* why did i add this? bcoz fking linkInReader state is showing initial only in App.tsx
*/
linkInReader: {
link: string;
page: number;
};

// to remove later
keydown: boolean;
};
Expand Down Expand Up @@ -436,13 +451,18 @@ window.shortcutsFunctions = [
];
window.logger = log;
window.crossZip = crossZip;
window.chokidar = chokidar;
const collator = Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
window.app.betterSortOrder = collator.compare;
window.app.replaceExtension = (str) => {
return str.replace(/\.zip/gi, " [ZIP file]").replace(/\.cbz/gi, " [CBZ file]");
};
window.app.deleteDirOnClose = "";
window.app.currentPageNumber = 1;
window.app.linkInReader = {
link: "",
page: 1,
};
window.app.randomString = (length: number) => {
let result = "";
const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Expand Down
44 changes: 27 additions & 17 deletions src/store/bookmarks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,29 @@ import { bookmarksPath, saveJSONfile } from "../MainImports";

const initialState: ChapterItem[] = [];

if (window.fs.existsSync(bookmarksPath)) {
const raw = window.fs.readFileSync(bookmarksPath, "utf8");
if (raw) {
try {
const data = JSON.parse(raw);
initialState.push(...data);
} catch (err) {
window.dialog.customError({
message: "Unable to parse " + bookmarksPath + "\nMaking new bookmarks.json.",
});
window.logger.error(err);
window.fs.writeFileSync(bookmarksPath, "[]");
}
const readBookmark = (): ChapterItem[] => {
if (window.fs.existsSync(bookmarksPath)) {
const raw = window.fs.readFileSync(bookmarksPath, "utf8");
if (raw) {
try {
const data = JSON.parse(raw);
return data;
} catch (err) {
window.dialog.customError({
message: "Unable to parse " + bookmarksPath + "\nMaking new bookmarks.json.",
});
window.logger.error(err);
return [];
}
} else return [];
} else {
return [];
}
} else {
window.fs.writeFileSync(bookmarksPath, "[]");
}
};

const bookmarkData = readBookmark();
if (bookmarkData.length === 0) window.fs.writeFileSync(bookmarksPath, "[]");
initialState.push(...bookmarkData);

const bookmarks = createSlice({
name: "bookmarks",
Expand Down Expand Up @@ -60,6 +66,9 @@ const bookmarks = createSlice({
}
return state;
},
refreshBookmark: () => {
return readBookmark();
},
// action.payload : link of chapter
removeBookmark: (state, action: PayloadAction<string>) => {
const newState = state.filter((e) => e.link !== action.payload);
Expand All @@ -73,6 +82,7 @@ const bookmarks = createSlice({
},
});

export const { addBookmark, removeAllBookmarks, removeBookmark, updateBookmark } = bookmarks.actions;
export const { addBookmark, removeAllBookmarks, removeBookmark, updateBookmark, refreshBookmark } =
bookmarks.actions;

export default bookmarks.reducer;
92 changes: 60 additions & 32 deletions src/store/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,35 @@ import { historyPath, saveJSONfile } from "../MainImports";

const initialState: HistoryItem[] = [];

if (window.fs.existsSync(historyPath)) {
const raw = window.fs.readFileSync(historyPath, "utf8");
if (raw) {
try {
const data = JSON.parse(raw);
if (data[0] && !data[0].chaptersRead) throw new Error("History format changed.");
initialState.push(...data);
} catch (err) {
if ((err as Error).message === "History format changed.")
window.dialog.customError({
message: "History format changed.\nSorry for the inconvenience.",
});
else
window.dialog.customError({
message: "Unable to parse " + historyPath + "\nMaking new history.json...",
});
window.logger.error(err);
window.fs.writeFileSync(historyPath, "[]");
}
const readHistory = (): HistoryItem[] => {
if (window.fs.existsSync(historyPath)) {
const raw = window.fs.readFileSync(historyPath, "utf8");
if (raw) {
try {
const data = JSON.parse(raw);
if (data[0] && !data[0].chaptersRead) throw new Error("History format changed.");
return data;
} catch (err) {
if ((err as Error).message === "History format changed.")
window.dialog.customError({
message: "History format changed.\nSorry for the inconvenience.",
});
else
window.dialog.customError({
message: "Unable to parse " + historyPath + "\nMaking new history.json...",
});
window.logger.error(err);
return [];
}
} else return [];
} else {
return [];
}
} else {
window.fs.writeFileSync(historyPath, "[]");
}
};

const historyData = readHistory();
if (historyData.length === 0) window.fs.writeFileSync(historyPath, "[]");
initialState.push(...historyData);

const history = createSlice({
name: "history",
Expand All @@ -51,27 +57,49 @@ const history = createSlice({
saveJSONfile(historyPath, state);
},
// todo: getlink from state directly;
updateLastHistoryPage: (state, action: PayloadAction<{ linkInReader: string }>) => {
if (
(state.length > 0 && state[0] && state[0].link && state[0].link === action.payload.linkInReader) ||
action.payload.linkInReader === ""
) {
state[0].page = window.app.currentPageNumber;
saveJSONfile(historyPath, state);
// todo: fix; when called in App.tsx linkInReader is initialVlue even if changed
// updateLastHistoryPage: (state, action: PayloadAction<{ linkInReader: string }>) => {
// const index = state.findIndex((e) => e.link === action.payload.linkInReader);
// // todo : removed ` || action.payload.linkInReader === ""`; check consequences
// // not working on closing window
// // use sth like window.lastMangaOpened;
// window.logger.log("asking to save ", action.payload);
// if (index > -1) {
// console.log(`Updating ${state[index].mangaName} to page ${window.app.currentPageNumber}`);
// state[index].page = window.app.currentPageNumber;
// saveJSONfile(historyPath, state);
// }
// },
updateLastHistoryPage: (state) => {
const stateDup = [...state];
const link = window.app.linkInReader.link;
const index = stateDup.findIndex((e) => e.link === link);
// not working on closing window
// use sth like window.lastMangaOpened;
// window.logger.log("asking to save ", link);
if (index > -1) {
// console.log(`Updating ${stateDup[index].mangaName} to page ${window.app.currentPageNumber}`);
stateDup[index].page = window.app.currentPageNumber;
saveJSONfile(historyPath, stateDup);
}
return state;
},
refreshHistory: () => {
let newState = readHistory();
if (newState.length === 0) newState = readHistory();
return newState;
},
removeHistory: (state, action: PayloadAction<number>) => {
state.splice(action.payload, 1);
saveJSONfile(historyPath, state);
},
deleteAllHistory: (state) => {
deleteAllHistory: () => {
saveJSONfile(historyPath, []);
return [];
},
},
});

export const { newHistory, updateLastHistoryPage, deleteAllHistory, removeHistory } = history.actions;
export const { newHistory, updateLastHistoryPage, deleteAllHistory, removeHistory, refreshHistory } =
history.actions;

export default history.reducer;
6 changes: 3 additions & 3 deletions src/store/linkInReader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ import { createSlice, PayloadAction } from "@reduxjs/toolkit";

const initialState = {
link: window.loadManga || "",
page: 1,
page: 5,
};

const linkInReader = createSlice({
name: "linkInReader",
initialState,
reducers: {
setLinkInReader: (state, action: PayloadAction<{ link: string; page: number }>) => {
return action.payload;
setLinkInReader: (state, action: PayloadAction<typeof initialState>) => {
return { ...action.payload };
},
},
});
Expand Down
8 changes: 8 additions & 0 deletions webpack/main.webpack.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
const { IgnorePlugin } = require('webpack');

const optionalPlugins = [];
if (process.platform !== "darwin") {
optionalPlugins.push(new IgnorePlugin({ resourceRegExp: /^fsevents$/ }));
}

module.exports = {
resolve: {
extensions: [".ts", ".js"],
Expand All @@ -6,4 +13,5 @@ module.exports = {
module: {
rules: require("./rules.webpack"),
},
plugins:[...optionalPlugins]
};
11 changes: 10 additions & 1 deletion webpack/renderer.webpack.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
const { IgnorePlugin } = require('webpack');

const optionalPlugins = [];
if (process.platform !== "darwin") {
optionalPlugins.push(new IgnorePlugin({ resourceRegExp: /^fsevents$/ }));
}


module.exports = {
resolve: {
extensions: [".ts", ".tsx", ".js"],
Expand All @@ -8,6 +16,7 @@ module.exports = {
externals: {
electron: 'commonjs2 electron',
},
target: 'electron-renderer'
target: 'electron-renderer',
plugins:[...optionalPlugins]
// target: "web",
};
Loading

0 comments on commit e77e3a4

Please sign in to comment.