ResourceWatcherFSM.cpp 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858
  1. #include "stdafx.h"
  2. #include "ResourceWatcherFSM.h"
  3. #include "DeviceBaseClass.h"
  4. #include <string.h>
  5. #if defined(RVC_OS_WIN)
  6. #include <intrin.h>
  7. #include <ShlObj.h>
  8. #include <Pdh.h>
  9. #include "shellapi.h"
  10. #include "Mmdeviceapi.h"
  11. #include "Propidl.h"
  12. #include "Functiondiscoverykeys_devpkey.h"
  13. #include "PolicyConfig.h"
  14. #endif //RVC_OS_WIN
  15. #include <assert.h>
  16. #include <algorithm>
  17. #include "fileutil.h"
  18. const int DEFAULT_DAY_OF_BACKWARD = 90;
  19. const int MAX_DAY_OF_BACKWARD = 365;
  20. const char * DEFAULT_DELETE_FILE_SUFFIX = "*";
  21. LPCTSTR UPLOAD_VIDEO_PATH = "UploadVideo";
  22. const int AD0_DAY_OF_BACKWARD = 7;
  23. const int TIMER_INTERVAL_CLEARVIDEO_ENHANCE = 60 * 1000;
  24. const int MAX_VERSION_PATH = 256;
  25. //保留版本数目
  26. const int DEFAULT_VERSION_SAVED_COUNT = 2;
  27. CRITICAL_SECTION g_csVideoMoreClear;
  28. #define MAX_VOLUME_COUNT 26
  29. #define BUFSIZE 512
  30. static BOOL sBDiskValStatus[MAX_VOLUME_COUNT + 1] = { FALSE };
  31. #define MAX_SUBFILES_COUNT 1000
  32. #define DIV (1024 * 1024)
  33. #define DAY_DIV (24 * 60 * 60)
  34. #define HOURS_DIV (60 * 60)
  35. #define MINUS_DIV (60)
  36. const char * SystemElapsedQuery = "\\System\\System Up Time";
  37. template<class T>
  38. class TimerOutHelper : public ITimerListener
  39. {
  40. public:
  41. typedef void (T::*FuncTimer)();
  42. TimerOutHelper(T *p, FuncTimer pTimerFunc, bool bDeleteSelf = false)
  43. : m_pObject(p), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf) {}
  44. virtual void OnTimeout(DWORD dwTimerID)
  45. {
  46. (m_pObject->*m_pTimer)();
  47. if (m_bDeleteSelf)
  48. delete this;
  49. }
  50. private:
  51. T *m_pObject;
  52. FuncTimer m_pTimer;
  53. bool m_bDeleteSelf;
  54. };
  55. ResourceWatcherFSM::ResourceWatcherFSM(void)
  56. :m_IsPadDevice(FALSE)
  57. , m_bGetStatusRotate(FALSE)
  58. ,m_uploadedVideoDirPath(true)
  59. , m_csDelFileSuffix(true)
  60. ,m_nDayOfBackward(DEFAULT_DAY_OF_BACKWARD)
  61. , m_failDelCnt(0)
  62. , m_bReadyFlag(false)
  63. , m_bVideoClearReady(false)
  64. , m_nMinSavedDay(DEFAULT_SAVE_DATE_COUNT)
  65. , m_highPart(0)
  66. ,m_lowPart(0)
  67. , m_strTerminalNo(true)
  68. {
  69. #if defined(_MSC_VER)
  70. mUiRequireBytes.QuadPart = 0;
  71. mUiCalibration.QuadPart = 0;
  72. #else
  73. mAllVideoFileSizeCal = 0;
  74. mMaxFileSize = 0;
  75. mUiCalibration = 0;
  76. mUiRequireBytes = 0;
  77. mftAd0RemoveTime = 0;
  78. #endif //_MSC_VER
  79. }
  80. ResourceWatcherFSM::~ResourceWatcherFSM(void)
  81. {
  82. }
  83. void ResourceWatcherFSM::ClearVideoQueue()
  84. {
  85. while (!m_VideoFiles.empty()) {
  86. TmpFileInfo* pNodeInfo = m_VideoFiles.top();
  87. m_VideoFiles.pop();
  88. if (pNodeInfo != NULL) {
  89. delete pNodeInfo;
  90. }
  91. }
  92. memset(szMaxSizeFilePath, 0, sizeof(szMaxSizeFilePath));
  93. #if defined(_MSC_VER)
  94. mAllVideoFileSizeCal.QuadPart = 0ui64;
  95. mMaxFileSize.QuadPart = 0ui64;
  96. mUiRequireBytes.QuadPart = 0ui64;
  97. #else
  98. mAllVideoFileSizeCal = 0;
  99. mMaxFileSize = 0;
  100. mUiRequireBytes = 0;
  101. #endif //_MSC_VER
  102. VideoDailyRecord.clear();
  103. }
  104. void ResourceWatcherFSM::PrintVideEmurateResult()
  105. {
  106. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  107. #if defined(_MSC_VER)
  108. ByteSprintf(szResult, (double)mMaxFileSize.QuadPart);
  109. Dbg("Max Video file: %s size: %s", szMaxSizeFilePath, szResult);
  110. Dbg("mAllVideoFileSizeCal.QuadPart : %I64u Bytes", mAllVideoFileSizeCal.QuadPart);
  111. ByteSprintf(szResult, (double)mAllVideoFileSizeCal.QuadPart);
  112. #else
  113. ByteSprintf(szResult, (double)mMaxFileSize);
  114. Dbg("Max Video file: %s size: %s", szMaxSizeFilePath, szResult);
  115. Dbg("mAllVideoFileSizeCal : %llu Bytes", mAllVideoFileSizeCal);
  116. ByteSprintf(szResult, (double)mAllVideoFileSizeCal);
  117. #endif //_MSC_VER
  118. Dbg("Totally(size: %d) directory size: %s", m_VideoFiles.size(), szResult);
  119. }
  120. void ResourceWatcherFSM::s0_on_entry()
  121. {
  122. LOG_FUNCTION();
  123. this->PostEventFIFO(new RunEvent());
  124. GetCpuType(NULL);
  125. }
  126. unsigned int ResourceWatcherFSM::s0_on_event(FSMEvent* e)
  127. {
  128. LOG_FUNCTION();
  129. unsigned int unRes = 0;
  130. switch(e->iEvt)
  131. {
  132. case USER_EVT_RUN:
  133. {
  134. if(m_IsPadDevice) {
  135. GetCardSwiperTask* task = new GetCardSwiperTask(this);
  136. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  137. }
  138. #if 0
  139. ClearVideoFilesTask* videoTask = new ClearVideoFilesTask(this);
  140. videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
  141. GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
  142. GetEntityBase()->GetFunction()->PostThreadPoolTask(new ClearCenterSettingFilesTask(this));
  143. GetEntityBase()->GetFunction()->PostThreadPoolTask(new ClearAd0Task(this));
  144. #else
  145. RunTask* videoTask = new RunTask(this);
  146. videoTask->SetFlag(m_bReadyFlag ? 1 : 0);
  147. GetEntityBase()->GetFunction()->PostThreadPoolTask(videoTask);
  148. #endif
  149. e->SetHandled();
  150. }
  151. break;
  152. case USER_EVT_FETCH:
  153. {
  154. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  155. fetchEvt->ctx->Answer(Error_InvalidState);
  156. e->SetHandled();
  157. }
  158. break;
  159. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  160. {
  161. m_bGetStatusRotate = FALSE;
  162. e->SetHandled();
  163. }
  164. break;
  165. default:
  166. {
  167. Dbg("Unexpecetd Event(%d)", e->iEvt);
  168. }
  169. break;
  170. }
  171. return unRes;
  172. }
  173. void ResourceWatcherFSM::s0_on_exit()
  174. {
  175. }
  176. void ResourceWatcherFSM::s1_on_entry()
  177. {
  178. LOG_FUNCTION();
  179. }
  180. unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
  181. {
  182. LOG_FUNCTION();
  183. unsigned int unRes = 0;
  184. switch(e->iEvt)
  185. {
  186. case USER_EVT_FETCH:
  187. {
  188. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  189. if(m_IsPadDevice)
  190. {
  191. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  192. fetchEvt->ctx->Answer(Error_Succeed);
  193. }
  194. else
  195. {
  196. Dbg("In Not Pad MachineType, Receive Query CardSwiper Status Event");
  197. fetchEvt->ctx->Answer(Error_NotSupport);
  198. }
  199. e->SetHandled();
  200. }
  201. break;
  202. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  203. {
  204. m_bGetStatusRotate = FALSE;
  205. e->SetHandled();
  206. }
  207. break;
  208. case USER_EVT_CLEAR_UPLOADEDVIDEOFILES_FINISHED:
  209. {
  210. Dbg("%s::There are %d file(s), successfully delete %d file(s) in path %s", __FUNCTION__,
  211. e->param2, e->param1, (LPCTSTR)m_uploadedVideoDirPath);
  212. if(m_failDelCnt != 0) {
  213. CSimpleStringA strMsg = CSimpleStringA::Format("There are %d matched files should be deleted", m_failDelCnt);
  214. LogWarn(Severity_Middle, Error_Unexpect, 0, (LPCTSTR)strMsg);
  215. }
  216. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  217. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  218. }
  219. e->SetHandled();
  220. break;
  221. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  222. {
  223. PostEventFIFO(new FSMEvent(USER_EVT_VERSION_CLEAR));
  224. }
  225. e->SetHandled();
  226. break;
  227. case USER_EVT_VERSION_CLEAR:
  228. {
  229. ClearVersionTask* task = new ClearVersionTask(this);
  230. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  231. }
  232. e->SetHandled();
  233. break;
  234. case USER_EVT_VERSION_CLEAR_FINISHED:
  235. e->SetHandled();
  236. break;
  237. default:
  238. {
  239. Dbg("Unexpecetd Event(%d)", e->iEvt);
  240. }
  241. break;
  242. }
  243. return unRes;
  244. }
  245. void ResourceWatcherFSM::s1_on_exit()
  246. {
  247. }
  248. void ResourceWatcherFSM::s2_on_entry()
  249. {
  250. LOG_FUNCTION();
  251. }
  252. unsigned int ResourceWatcherFSM::s2_on_event(FSMEvent* e)
  253. {
  254. LOG_FUNCTION();
  255. unsigned int unRes = 0;
  256. switch(e->iEvt)
  257. {
  258. case USER_EVT_RUN:
  259. {
  260. e->SetHandled();
  261. }
  262. break;
  263. case USER_EVT_FETCH:
  264. {
  265. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  266. if(m_IsPadDevice)
  267. {
  268. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  269. fetchEvt->ctx->Answer(Error_Succeed);
  270. }
  271. else
  272. {
  273. Dbg("In Not Pad MachineType, Receive Query CardSwiper Status Event");
  274. fetchEvt->ctx->Answer(Error_NotSupport);
  275. }
  276. e->SetHandled();
  277. }
  278. break;
  279. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  280. {
  281. m_bGetStatusRotate = FALSE;
  282. e->SetHandled();
  283. }
  284. break;
  285. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  286. {
  287. }
  288. e->SetHandled();
  289. break;
  290. }
  291. return unRes;
  292. }
  293. void ResourceWatcherFSM::s2_on_exit()
  294. {
  295. LOG_FUNCTION();
  296. }
  297. void ResourceWatcherFSM::s3_on_entry()
  298. {
  299. LOG_FUNCTION();
  300. m_bVideoClearReady = true;
  301. }
  302. unsigned int ResourceWatcherFSM::s3_on_event(FSMEvent* e)
  303. {
  304. LOG_FUNCTION();
  305. unsigned int unRes = 0;
  306. switch(e->iEvt)
  307. {
  308. case USER_EVT_RUN:
  309. {
  310. e->SetHandled();
  311. }
  312. break;
  313. case USER_EVT_FETCH:
  314. {
  315. FetchEvent* fetchEvt = dynamic_cast<FetchEvent*>(e);
  316. if(m_IsPadDevice)
  317. {
  318. fetchEvt->ctx->Ans.reserved1 = GetCardSwiperVal();
  319. fetchEvt->ctx->Answer(Error_Succeed);
  320. }
  321. else
  322. {
  323. Dbg("In Not Pad MachineType, Receive Query CardSwiper Status Event");
  324. fetchEvt->ctx->Answer(Error_NotSupport);
  325. }
  326. e->SetHandled();
  327. }
  328. break;
  329. case USER_EVT_GET_CARDSWIPER_STATUS_FINISHED:
  330. {
  331. m_bGetStatusRotate = FALSE;
  332. e->SetHandled();
  333. }
  334. break;
  335. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE:
  336. {
  337. ClearVideoFilesEnhanceTask* task = new ClearVideoFilesEnhanceTask(this);
  338. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  339. }
  340. e->SetHandled();
  341. break;
  342. case USER_EVT_CLEAR_VIDEOFILE_ENHANCE_FINISHED:
  343. {
  344. }
  345. e->SetHandled();
  346. break;
  347. case USER_EVT_FILE_OPERAT:
  348. {
  349. OperateFileEvent* theEvt = dynamic_cast<OperateFileEvent*>(e);
  350. OperateFileTask* theTask = new OperateFileTask(this, theEvt->m_ctx);
  351. GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
  352. }
  353. e->SetHandled();
  354. break;
  355. case USER_EVT_FILE_OPERAT_FINISHED:
  356. {
  357. }
  358. e->SetHandled();
  359. break;
  360. case USER_EVT_GET_EVENTLOG:
  361. {
  362. GetEventLogEvent* theEvt = dynamic_cast<GetEventLogEvent*>(e);
  363. #if defined(_MSC_VER)
  364. GetEventLogTask* theTask = new GetEventLogTask(this, theEvt->m_ctx);
  365. GetEntityBase()->GetFunction()->PostThreadPoolTask(theTask);
  366. #else
  367. theEvt->m_ctx->Answer(Error_NotSupport);
  368. #endif //_MSC_VER
  369. }
  370. e->SetHandled();
  371. break;
  372. case USER_EVT_GET_EVENTLOG_FINISHED:
  373. {
  374. }
  375. e->SetHandled();
  376. break;
  377. }
  378. return unRes;
  379. }
  380. void ResourceWatcherFSM::s3_on_exit()
  381. {
  382. m_bVideoClearReady = false;
  383. }
  384. void ResourceWatcherFSM::readVideoStoreData()
  385. {
  386. LOG_FUNCTION();
  387. CSmartPointer<IConfigInfo> spCtSettingConfig;
  388. CSmartPointer<IConfigInfo> spConfig;
  389. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  390. GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
  391. // From CenterSetting --Josephus at 10:02:10 201759
  392. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "BackwardDays", m_nDayOfBackward);
  393. if (m_nDayOfBackward <= 0) {
  394. spConfig->ReadConfigValueInt("Video", "BackwardDays", m_nDayOfBackward);
  395. } else {
  396. Dbg("Detect BackwardDays from CentralSetting %d", m_nDayOfBackward);
  397. }
  398. if (m_nDayOfBackward <= 0 || m_nDayOfBackward > MAX_DAY_OF_BACKWARD) {
  399. Dbg("Detect BackwardDays(%d) is illegal and Set default %d", m_nDayOfBackward, DEFAULT_DAY_OF_BACKWARD);
  400. m_nDayOfBackward = DEFAULT_DAY_OF_BACKWARD;
  401. }
  402. int minSavedDay = 0;
  403. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MinSavedDays", minSavedDay);
  404. if (minSavedDay >= 1 && minSavedDay < DEFAULT_SAVE_DATE_COUNT) {
  405. m_nMinSavedDay = minSavedDay;
  406. Dbg("Detect MinSavedDays from CentralSetting %d", m_nMinSavedDay);
  407. }
  408. }
  409. ErrorCodeEnum ResourceWatcherFSM::OnInit()
  410. {
  411. #if defined(_MSC_VER) && defined(WIDE_CONDITION)
  412. setlocale(LC_ALL, "chs");
  413. #endif
  414. //Dbg("Complied at: %s %s", __DATE__, __TIME__);
  415. ErrorCodeEnum erroCode = Error_Succeed;
  416. CSystemStaticInfo sysInfo;
  417. erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(sysInfo);
  418. if(erroCode != Error_Succeed) {
  419. Dbg("Get System Static info failed: %s.", SpStrError(erroCode));
  420. return Error_Unexpect;
  421. }
  422. Dbg("%s, %s", sysInfo.strMachineType.GetData(), sysInfo.strTerminalID.GetData());
  423. //LOG_TRACE("here: %s, %s", sysInfo.strMachineType.GetData(), sysInfo.strTerminalID.GetData());
  424. m_strTerminalNo = sysInfo.strTerminalID;
  425. if(!sysInfo.strMachineType.Compare("RVC.Pad", true)) {
  426. m_IsPadDevice = TRUE;
  427. }
  428. erroCode = GetEntityBase()->GetFunction()->GetPath("LocalVideo", m_uploadedVideoDirPath);
  429. if (erroCode != Error_Succeed || m_uploadedVideoDirPath.IsNullOrEmpty()) {
  430. return Error_NotInit;
  431. }
  432. const BOOL bFirstRun = DetectIsFirstRunAtBoot();
  433. Dbg("to initialize critical section...");
  434. InitializeCriticalSection(&g_csVideoMoreClear);
  435. InitialVolumes();
  436. InitBlackList();
  437. readVideoStoreData();
  438. m_bReadyFlag = IsNeedToFirstClear();
  439. Dbg("Retrieve uploadedVideo path[%s], backwardDays(%d) done(%d)"
  440. , (LPCTSTR)m_uploadedVideoDirPath, m_nDayOfBackward, !m_bReadyFlag);
  441. #if defined(_MSC_VER)
  442. if (!sysInfo.strMachineType.Compare("RVC.Desk2S", true)) {
  443. int nLastTaskTime(0);
  444. CSmartPointer<IConfigInfo> spRunConfig;
  445. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  446. spRunConfig->ReadConfigValueInt("Device", "SetAudioOutput", nLastTaskTime);
  447. CSmallDateTime lastSetTime(nLastTaskTime);
  448. Dbg("RunConfig SetAudioOutput time : %s", (LPCTSTR)lastSetTime.ToTimeString());
  449. if (bFirstRun) {
  450. Dbg("last set audio output time is earlier than system boot time!");
  451. Dbg("Start to Set Audio output device");
  452. if (SetDefaultAudioDevice()) {
  453. spRunConfig->WriteConfigValue("Device", "SetAudioOutput", CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  454. } else {
  455. LogWarn(Severity_Middle, Error_AudioOut, 0, "Set default video output failed!!");
  456. }
  457. }
  458. }
  459. #endif //_MSC_VER
  460. return Error_Succeed;
  461. }
  462. ErrorCodeEnum ResourceWatcherFSM::OnExit()
  463. {
  464. LOG_FUNCTION();
  465. ClearVideoQueue();
  466. DeleteCriticalSection(&g_csVideoMoreClear);
  467. return Error_Succeed;
  468. }
  469. int ResourceWatcherFSM::GetCardSwiperStatus()
  470. {
  471. LOG_FUNCTION();
  472. ErrorCodeEnum errorCode = Error_Succeed;
  473. CardSwiperClient* client = NULL;
  474. CardSwiperService_QueryConnInfo_Req req;
  475. CardSwiperService_QueryConnInfo_Ans ans;
  476. QueryCardSwiper cardswiperStatus;
  477. BOOL bConnected = FALSE;
  478. // [Josephus in 7:05:25 2016/9/6]
  479. int lastStatus = m_cardswiperStatus;
  480. int errorTimes1 = 0, errorTimes2 = 0, errorTimes3 = 0;
  481. int sleepTime = 1500;
  482. const int errorMaxTimes = 2;
  483. m_bGetStatusRotate = TRUE;
  484. while(m_bGetStatusRotate)
  485. {
  486. if(client == NULL)
  487. {
  488. client = new CardSwiperClient(GetEntityBase());
  489. }
  490. if(!bConnected)
  491. {
  492. errorCode = client->Connect();
  493. if(errorCode != Error_Succeed)
  494. {
  495. if(errorTimes1 < errorMaxTimes)
  496. {
  497. errorTimes1++;
  498. Dbg("Connect to CardSwiper failed %s", SpStrError(errorCode));
  499. Sleep(500);
  500. continue;
  501. }
  502. else
  503. {
  504. //errorTimes1++;
  505. Dbg("Connect to CardSwiper failed...");
  506. // [Josephus in 16:15:37 2016/3/28]
  507. bConnected = FALSE;
  508. client->SafeDelete();
  509. client = NULL;
  510. m_cardswiperStatus = 0;
  511. goto BroadCastPoint;
  512. }
  513. }
  514. else
  515. {
  516. Dbg("Connect to CardSwiper Success");
  517. bConnected = TRUE;
  518. errorTimes3 = errorTimes2 = 0;
  519. }
  520. }
  521. errorCode = client->QueryConnInfo(req, ans, 3000);
  522. if(errorCode != Error_Succeed)
  523. {
  524. if(errorTimes2 < errorMaxTimes)
  525. {
  526. errorTimes2++;
  527. Dbg("Get CardSwiper status failed with code %s", SpStrError(errorCode));
  528. Sleep(500);
  529. continue;
  530. }
  531. else
  532. {
  533. Dbg("Get CardSwiper status failed...");
  534. bConnected = FALSE;
  535. client->GetFunction()->CloseSession();
  536. client = NULL;
  537. m_cardswiperStatus = 0;
  538. }
  539. }
  540. else
  541. {
  542. errorTimes1 = errorTimes2 = errorTimes3 = 0;
  543. m_cardswiperStatus = ans.connect;
  544. }
  545. BroadCastPoint:
  546. if(lastStatus != m_cardswiperStatus)
  547. {
  548. Dbg("send broadcast for cardswiper status %d", m_cardswiperStatus);
  549. cardswiperStatus.status = m_cardswiperStatus;
  550. SpSendBroadcast(GetEntityBase()->GetFunction(),
  551. SP_MSG_OF(QueryCardSwiper), SP_MSG_SIG_OF(QueryCardSwiper), cardswiperStatus);
  552. lastStatus = m_cardswiperStatus;
  553. }
  554. break;
  555. }
  556. if(client)
  557. {
  558. if (bConnected) {
  559. client->GetFunction()->CloseSession();
  560. } else {
  561. client->SafeDelete();
  562. }
  563. client = NULL;
  564. }
  565. return 0;
  566. }
  567. void ResourceWatcherFSM::AppendVideoSizeTogether()
  568. {
  569. Dbg("Add UploadFile size together...");
  570. #if defined(_MSC_VER)
  571. ULARGE_INTEGER uiAdditionBytes;
  572. CalculateWillUploadDirSize(uiAdditionBytes);
  573. mAllVideoFileSizeCal.QuadPart += uiAdditionBytes.QuadPart;
  574. diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
  575. #else
  576. unsigned long long uiAdditionBytes;
  577. CalculateWillUploadDirSize(uiAdditionBytes);
  578. mAllVideoFileSizeCal += uiAdditionBytes;
  579. diskInfo.SetUploadVideoDirSize(uiAdditionBytes);
  580. #endif //_MSC_VER
  581. }
  582. void ResourceWatcherFSM::CalculateFreeDiskNeeded()
  583. {
  584. const_map_cu_iter citer = VideoDailyRecord.cbegin();
  585. UINT uCount = 0;
  586. while (citer != VideoDailyRecord.cend()) {
  587. Dbg("date[%d]: %d", (citer->first), citer->second);
  588. uCount += citer->second;
  589. citer++;
  590. }
  591. Dbg("count %d and video file size#%d", uCount, m_VideoFiles.size());
  592. diskInfo.CalAverRequreSpaceEachDay(mAllVideoFileSizeCal,
  593. uCount, VideoDailyRecord.size(),
  594. BASE_AVAILALBE_DATE_COUNT, mUiRequireBytes);
  595. }
  596. void ResourceWatcherFSM::RecordFreeDiskNeededToRunCfg()
  597. {
  598. CSmartPointer<IConfigInfo> spConfigRun;
  599. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  600. #if defined(RVC_OS_WIN)
  601. spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
  602. #else
  603. spConfigRun->WriteConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes);
  604. #endif //RVC_OS_WIN
  605. spConfigRun->WriteConfigValue("LastClearTime", "Video", (const char*)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  606. m_bReadyFlag = false;
  607. }
  608. void ResourceWatcherFSM::GetFreeDiskNeededFromRunCfg()
  609. {
  610. CSmartPointer<IConfigInfo> spConfigRun;
  611. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  612. #if defined(_MSC_VER)
  613. spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", mUiRequireBytes.QuadPart);
  614. Dbg("Retrieve from runcfg about required bytes: %llu", mUiRequireBytes.QuadPart);
  615. #else
  616. UINT64 value(0);
  617. spConfigRun->ReadConfigValueHexInt("Video", "RequiredBytes", value);
  618. mUiRequireBytes = value;
  619. Dbg("Retrieve from runcfg about required bytes: %llu", value);
  620. #endif //_MSC_VER
  621. }
  622. int ResourceWatcherFSM::CleanVideoFiles(int& newDeletedFilesNum, int initFlag)
  623. {
  624. LOG_FUNCTION();
  625. newDeletedFilesNum = 0;
  626. ClearVideoQueue();
  627. CSimpleStringA filePath = m_uploadedVideoDirPath;
  628. #if defined(_MSC_VER)
  629. filePath += "\\*";
  630. #endif //_MSC_VER
  631. Dbg("(InitFlag:%d) filePath %s", initFlag, (LPCTSTR)filePath);
  632. newDeletedFilesNum = 0;
  633. m_failDelCnt = 0;
  634. const int nRet = RemoveExpireVideoFileAndRecord((LPCTSTR)filePath, newDeletedFilesNum, m_failDelCnt, initFlag);
  635. PrintVideEmurateResult();
  636. Dbg("nRet: %d, new Deleted Files Num:%d, video counts:%d", nRet, newDeletedFilesNum, m_VideoFiles.size());
  637. LOG_ASSERT(nRet - newDeletedFilesNum == m_VideoFiles.size());
  638. if(!!initFlag) {
  639. AppendVideoSizeTogether();
  640. CalculateFreeDiskNeeded();
  641. RecordFreeDiskNeededToRunCfg();
  642. } else {
  643. GetFreeDiskNeededFromRunCfg();
  644. }
  645. return nRet;
  646. }
  647. #if defined(RVC_OS_WIN)
  648. void ResourceWatcherFSM::CalculateBackTime(PFILETIME ftResultTime, int days)
  649. {
  650. //Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
  651. FILETIME ftCurTime, ftBackTime;
  652. GetSystemTimeAsFileTime(&ftCurTime);
  653. ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
  654. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  655. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  656. if (days > 0) {
  657. uliOffset.QuadPart = UInt32x32To64(days * 24 * 60 * 60, 1e7);
  658. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  659. } else {
  660. uliOffset.QuadPart = UInt32x32To64(-1 * days * 24 * 60 * 60, 1e7);
  661. uliBackTime.QuadPart = uliCurTime.QuadPart + uliOffset.QuadPart;
  662. }
  663. ftBackTime.dwHighDateTime = uliBackTime.HighPart;
  664. ftBackTime.dwLowDateTime = uliBackTime.LowPart;
  665. *ftResultTime = ftBackTime;
  666. return;
  667. }
  668. BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(ULARGE_INTEGER& uiBytesCal)
  669. {
  670. uiBytesCal.QuadPart = 0;
  671. #else
  672. void ResourceWatcherFSM::CalculateBackTime(time_t* ftResultTime, int days)
  673. {
  674. time_t ftCurTime = time(NULL);//获取当前时间
  675. time_t ftBackTime = ftCurTime - (60 * 60 * 24 * days);
  676. *ftResultTime = ftBackTime;
  677. return;
  678. }
  679. BOOL ResourceWatcherFSM::CalculateWillUploadDirSize(unsigned long long& uiBytesCal)
  680. {
  681. uiBytesCal = 0;
  682. #endif //RVC_OS_WIN
  683. BOOL bRet = FALSE;
  684. CSimpleStringA uploadVideoPath;
  685. CSimpleStringA tmpValue;
  686. ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPath(UPLOAD_VIDEO_PATH, uploadVideoPath);
  687. if (uploadVideoPath.GetLength() <= 0) ec = Error_Param;
  688. if (ec == Error_Succeed) {
  689. Dbg("UploadVideo path: %s", (LPCTSTR)uploadVideoPath);
  690. #if defined(_MSC_VER)
  691. CSimpleStringA filePath = uploadVideoPath + "\\*";
  692. ULARGE_INTEGER uliSpaceSize;
  693. uliSpaceSize.QuadPart = 0;
  694. int nFileCnt = CalculateAllVideoSize(filePath, &uliSpaceSize);
  695. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  696. ByteSprintf(szResult, (double)uliSpaceSize.QuadPart);
  697. uiBytesCal.QuadPart = uliSpaceSize.QuadPart;
  698. #else
  699. uiBytesCal = 0;
  700. const int nFileCnt = CalculateAllVideoSize(uploadVideoPath, &uiBytesCal);
  701. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  702. ByteSprintf(szResult, (double)uiBytesCal);
  703. #endif //_MSC_VER
  704. Dbg("Result: Files(%d), Size: %s", nFileCnt, szResult);
  705. }
  706. return (ec == Error_Succeed);
  707. }
  708. int ResourceWatcherFSM::RemoveExpireVideoFileAndRecord(LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt, const int nFlag)
  709. {
  710. int fileCnt = 0;
  711. int fileLength = strlen(dirName);
  712. // =>=> /*foundFileData.cFileName[0] != '.'*/ !!! be careful for backdate call for the function.
  713. char searchFilePath[MAX_PATH] = {0};
  714. char tempFilePath[MAX_PATH] = {0};
  715. char displayTime[MAX_PATH] = {0};
  716. #if defined(RVC_OS_WIN)
  717. WIN32_FIND_DATA foundFileData;
  718. HANDLE hFind;
  719. FILETIME ftRemoveTime;
  720. CalculateBackTime(&ftRemoveTime, m_nDayOfBackward);
  721. GetTimeFormatStr(displayTime, MAX_PATH, &ftRemoveTime);
  722. Dbg("The date backward to delete: %s", displayTime);
  723. hFind = FindFirstFile(dirName, &foundFileData);
  724. if (hFind == INVALID_HANDLE_VALUE) {
  725. Dbg("FindFirstFile failed (%u)", GetLastError());
  726. return 0;
  727. }
  728. do
  729. {
  730. if ((foundFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  731. if (/*foundFileData.cFileName[0] != '.'*/FALSE) {
  732. strcpy_s(tempFilePath, dirName);
  733. tempFilePath[fileLength - 1] = '\0';
  734. strcat_s(tempFilePath, foundFileData.cFileName);
  735. strcat_s(tempFilePath, "\\*");
  736. fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
  737. }
  738. } else {
  739. strcpy_s(searchFilePath, dirName);
  740. searchFilePath[fileLength - 1] = '\0';
  741. strcat_s(searchFilePath, foundFileData.cFileName);
  742. if (nFlag == 1 && CompareVideoFileTime(&ftRemoveTime, &foundFileData.ftLastWriteTime) >= 0) {
  743. GetTimeFormatStr(displayTime, MAX_PATH, &foundFileData.ftLastWriteTime);
  744. if (DeleteFile(searchFilePath) != 0) {
  745. deletedFileCnt++;
  746. Dbg("Delete matched %s(%s) suc.", foundFileData.cFileName, displayTime);
  747. } else {
  748. deleteFailedCnt++;
  749. Dbg("Delete matched %s(%s) failed(%d).",
  750. foundFileData.cFileName, displayTime, GetLastError());
  751. RecordVideoFileInfomation(searchFilePath, &foundFileData);
  752. }
  753. } else {
  754. RecordVideoFileInfomation(searchFilePath, &foundFileData);
  755. }
  756. fileCnt++;
  757. }
  758. } while (FindNextFile(hFind, &foundFileData));
  759. FindClose(hFind);
  760. #else
  761. time_t tmp_time;
  762. CalculateBackTime(&tmp_time, m_nDayOfBackward);
  763. deletedFileCnt = deleteFailedCnt = 0;
  764. GetTimeFormatStr(displayTime, MAX_PATH, &tmp_time);
  765. Dbg("video backtrace time: %s", displayTime);
  766. struct stat st;
  767. if (stat(dirName, &st) < 0 || !S_ISDIR(st.st_mode)) {
  768. return 0;
  769. }
  770. DIR* d = opendir(dirName);
  771. if (!d) {
  772. return 0;
  773. }
  774. struct dirent* dp = NULL;
  775. while ((dp = readdir(d)) != NULL) {
  776. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  777. continue;
  778. }
  779. strcpy(tempFilePath, dirName);
  780. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  781. Dbg("filePath is too long for current.");
  782. continue;
  783. }
  784. strcat(tempFilePath, "/");
  785. strcat(tempFilePath, dp->d_name);
  786. if (-1 == stat(tempFilePath, &st)) {
  787. Dbg("stat video file: %s error: %d", tempFilePath, errno);
  788. continue;
  789. }
  790. const bool isdir = !!(S_ISDIR(st.st_mode));
  791. if (isdir) {
  792. fileCnt += RemoveExpireVideoFileAndRecord((LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt, nFlag);
  793. } else {
  794. if (nFlag == 1 && st.st_mtime < tmp_time) {
  795. GetTimeFormatStr(displayTime, MAX_PATH, &st.st_mtime);
  796. if (RemoveFileA(tempFilePath)) {
  797. deletedFileCnt++;
  798. Dbg("Delete matched %s(%s) suc.", dp->d_name, displayTime);
  799. } else {
  800. deleteFailedCnt++;
  801. Dbg("Delete matched %s(%s) failed: %d", dp->d_name, displayTime, errno);
  802. }
  803. }
  804. RecordVideoFileInfomation(tempFilePath, &st);
  805. fileCnt++;
  806. }
  807. }
  808. closedir(d);
  809. #endif //RVC_OS_WIN
  810. return fileCnt;
  811. }
  812. #if defined(RVC_OS_WIN)
  813. BOOL ResourceWatcherFSM::GetCPUBrand(CSimpleStringA& csCpuBrand)
  814. {
  815. char CPUBrandString[0x40];
  816. int CPUInfo[4] = { -1 };
  817. unsigned nExIds;
  818. // Calling __cpuid with 0x80000000 as the InfoType argument
  819. // gets the number of valid extended IDs.
  820. __cpuid(CPUInfo, 0x80000000);
  821. nExIds = CPUInfo[0];
  822. memset(CPUBrandString, 0, sizeof(CPUBrandString));
  823. if (nExIds >= 0x80000004) {
  824. __cpuid(CPUInfo, 0x80000002);
  825. memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
  826. __cpuid(CPUInfo, 0x80000003);
  827. memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
  828. __cpuid(CPUInfo, 0x80000004);
  829. memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
  830. // Display all the information in user-friendly format.
  831. csCpuBrand = CPUBrandString;
  832. Dbg("CPU Brand String: %s", (LPCTSTR)csCpuBrand);
  833. return TRUE;
  834. }
  835. Dbg("Current device is not supported for getting cpu brand 0x%08x.", nExIds);
  836. return FALSE;
  837. }
  838. void ResourceWatcherFSM::InitialCPUMarkInfor()
  839. {
  840. ErrorCodeEnum erroCode = Error_Succeed;
  841. CSmartPointer<IConfigInfo> spConfig;
  842. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
  843. if(erroCode != Error_Succeed)
  844. {
  845. Dbg("Open Config_Software failed %s.", SpStrError(erroCode));
  846. return;
  847. }
  848. int nTmpValue1, nTmpValue2 = 0;
  849. erroCode = spConfig->ReadConfigValueInt("CPUMarkLevel", "High", nTmpValue1);
  850. if(erroCode == Error_Succeed/* && nTmpValue1 > 0*/)
  851. m_highPart = nTmpValue1;
  852. erroCode = spConfig->ReadConfigValueInt("CPUMarkLevel", "Low", nTmpValue2);
  853. if(erroCode == Error_Succeed/* && nTmpValue2 > 0*/)
  854. m_lowPart = nTmpValue2;
  855. Dbg("hight:%d > value >low:%d.", m_highPart, m_lowPart);
  856. return;
  857. }
  858. #endif //RVC_OS_WIN
  859. ErrorCodeEnum ResourceWatcherFSM::GetCpuType(
  860. SpReqAnsContext<ResourceWatcherService_GetCpuType_Req, ResourceWatcherService_GetCpuType_Ans>::Pointer ctx)
  861. {
  862. LOG_FUNCTION();
  863. ErrorCodeEnum ec = Error_Succeed;
  864. #if defined(RVC_OS_WIN)
  865. ErrorCodeEnum erroCode = Error_Succeed;
  866. CSimpleStringA csCPUBrand;
  867. if (!GetCPUBrand(csCPUBrand)) {
  868. if (ctx != NULL)
  869. ctx->Answer(Error_Unexpect);
  870. return Error_Unexpect;
  871. }
  872. CSmartPointer<IConfigInfo> spConfig;
  873. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Software, spConfig);
  874. if (erroCode != Error_Succeed) {
  875. Dbg("Open Config_Software failed 0x%x.", erroCode);
  876. if (ctx != NULL)
  877. ctx->Answer(Error_DevLoadFileFailed);
  878. return Error_DevLoadFileFailed;
  879. }
  880. int nMark = 0;
  881. int level = 0;
  882. erroCode = spConfig->ReadConfigValueInt("CPUMark", (LPCTSTR)csCPUBrand, nMark);
  883. if (erroCode != Error_Succeed || nMark == 0) {
  884. Dbg("There are no level information about %s(mark:%d)(code:%d).",
  885. (LPCTSTR)csCPUBrand, nMark, erroCode);
  886. if (ctx != NULL) {
  887. ctx->Ans.brand = csCPUBrand;
  888. ctx->Ans.level = 0;
  889. ctx->Ans.reserved1 = nMark;
  890. ctx->Ans.reserved2 = "";
  891. ctx->Answer(Error_Succeed);
  892. }
  893. } else {
  894. level = SelectMarkLevel(nMark);
  895. Dbg("Result: %s : %d(%d).", (LPCTSTR)csCPUBrand, nMark, level);
  896. if (ctx != NULL) {
  897. ctx->Ans.brand = csCPUBrand;
  898. ctx->Ans.level = level;
  899. ctx->Ans.reserved1 = nMark;
  900. ctx->Ans.reserved2 = "";
  901. ctx->Answer(Error_Succeed);
  902. }
  903. }
  904. return Error_Succeed;
  905. #else
  906. ec = Error_NotSupport;
  907. LogWarn(Severity_Middle, ec, 0, CSimpleStringA::Format("%s is not supported!", __FUNCTION__));
  908. if (ctx != NULL) {
  909. ctx->Answer(ec);
  910. }
  911. return ec;
  912. #endif //RVC_OS_WIN
  913. }
  914. BOOL ResourceWatcherFSM::RemoveDuplicateCenterSettingFiles()
  915. {
  916. LOG_FUNCTION();
  917. ErrorCodeEnum erroCode = Error_Succeed;
  918. CSmartPointer<IConfigInfo> spConfigRun;
  919. erroCode = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  920. if(erroCode != Error_Succeed) {
  921. Dbg("OpenConfig of 'Config_Run' failed 0x%x(%d).", erroCode, erroCode);
  922. return FALSE;
  923. }
  924. int nLastTaskTime(0);
  925. spConfigRun->ReadConfigValueInt("LastClearTime", "CenterSetting", nLastTaskTime);
  926. if (IsTodayDone(nLastTaskTime)) {
  927. return TRUE;
  928. }
  929. CSimpleStringA ssFilePath(true);
  930. erroCode = GetEntityBase()->GetFunction()->GetPath("cfg", ssFilePath);
  931. if(erroCode != Error_Succeed || ssFilePath.IsNullOrEmpty()) {
  932. Dbg("Get path of 'cfg' failed 0x%x(%d).", erroCode, erroCode);
  933. return FALSE;
  934. }
  935. #if defined(_MSC_VER)
  936. ssFilePath = ssFilePath + "\\*";
  937. #endif //_MSC_VER
  938. Dbg("filePath %s", (LPCTSTR)ssFilePath);
  939. int nDelSuc = 0;
  940. int nDelFailed = 0;
  941. int nfileSum = ClearSpecifieFile(DFT_CenterSetting, ssFilePath, nDelSuc, nDelFailed);
  942. Dbg("#CenterSetting#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
  943. spConfigRun->WriteConfigValue("LastClearTime", "CenterSetting", (const char*) CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  944. return TRUE;
  945. }
  946. int ResourceWatcherFSM::ClearSpecifieFile(DealFileType fileType, LPCTSTR dirName, int& deletedFileCnt, int& deleteFailedCnt)
  947. {
  948. LOG_FUNCTION();
  949. int nRes;
  950. int nfileCnt = 0;
  951. int fileLength = strlen(dirName);
  952. char searchFilePath[MAX_PATH] = {0};
  953. char tempFilePath[MAX_PATH] = {0};
  954. char displayTime[MAX_PATH] = {0};
  955. #if defined(RVC_OS_WIN)
  956. WIN32_FIND_DATA fndFileData;
  957. HANDLE hFind;
  958. hFind = FindFirstFile(dirName, &fndFileData);
  959. if (hFind == INVALID_HANDLE_VALUE) {
  960. printf("FindFirstFile failed (%d) \n", GetLastError());
  961. return -2;
  962. }
  963. do
  964. {
  965. if ((fndFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  966. if (fndFileData.cFileName[0] != '.') {
  967. memset(tempFilePath, 0, sizeof(tempFilePath));
  968. strcpy_s(tempFilePath, dirName);
  969. tempFilePath[fileLength - 1] = '\0';
  970. strcat_s(tempFilePath, fndFileData.cFileName);
  971. strcat_s(tempFilePath, "\\*");
  972. int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
  973. if (nRes >= 0) nfileCnt += nRes;
  974. }
  975. } else {
  976. memset((void*)searchFilePath, 0, MAX_PATH);
  977. strcpy_s(searchFilePath, dirName);
  978. searchFilePath[fileLength - 1] = '\0';
  979. strcat_s(searchFilePath, fndFileData.cFileName);
  980. if (fileType == DFT_Ad0) {
  981. if (CompareFileTime(&mftAd0RemoveTime, &fndFileData.ftLastWriteTime) >= 0) {
  982. nRes = RemoveSpecifiedFile(fileType, searchFilePath, fndFileData.cFileName);
  983. } else {
  984. nRes = 0;
  985. }
  986. } else {
  987. nRes = RemoveSpecifiedFile(fileType, searchFilePath, fndFileData.cFileName);
  988. }
  989. if (nRes == -1) deleteFailedCnt++;
  990. else if (nRes == 1) deletedFileCnt++;
  991. nfileCnt++;
  992. }
  993. } while (FindNextFile(hFind, &fndFileData));
  994. FindClose(hFind);
  995. #else
  996. struct stat st;
  997. if (stat(dirName, &st) < 0) {
  998. Dbg("stat for %s failed: %d %s", dirName, errno, strerror(errno));
  999. return -2;
  1000. }
  1001. if (!S_ISDIR(st.st_mode)) {
  1002. Dbg(" %s is not directory", dirName);
  1003. return -2;
  1004. }
  1005. DIR* d = opendir(dirName);
  1006. if (!d) {
  1007. return -3;
  1008. }
  1009. struct dirent* dp = NULL;
  1010. while ((dp = readdir(d)) != NULL) {
  1011. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1012. continue;
  1013. }
  1014. strcpy(tempFilePath, dirName);
  1015. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1016. Dbg("filePath is too long for current.");
  1017. continue;
  1018. }
  1019. strcat(tempFilePath, "/");
  1020. strcat(tempFilePath, dp->d_name);
  1021. Dbg("fileName: %s", dp->d_name);
  1022. struct stat stFile;
  1023. stat(tempFilePath, &stFile);
  1024. const bool isdir = !!(S_ISDIR(stFile.st_mode));
  1025. if (isdir && fileType != DFT_CenterSetting) {
  1026. int nRes = ClearSpecifieFile(fileType, (LPCTSTR)tempFilePath, deletedFileCnt, deleteFailedCnt);
  1027. if (nRes >= 0) nfileCnt += nRes;
  1028. } else if(!isdir) {
  1029. if (fileType != DFT_Ad0 || (CompareVideoFileTime(&mftAd0RemoveTime, &stFile.st_mtime) >= 0)) {
  1030. nRes = RemoveSpecifiedFile(fileType, tempFilePath, dp->d_name);
  1031. } else {
  1032. nRes = 0;
  1033. }
  1034. if (nRes == -1) deleteFailedCnt++;
  1035. else if (nRes == 1) deletedFileCnt++;
  1036. nfileCnt++;
  1037. }
  1038. }
  1039. closedir(d);
  1040. #endif //RVC_OS_WIN
  1041. return nfileCnt;
  1042. }
  1043. int ResourceWatcherFSM::RemoveSpecifiedFile(DealFileType fileType, LPCTSTR szFilePath, LPCTSTR szFileName)
  1044. {
  1045. CSimpleStringA ssFileName = szFileName;
  1046. if(ssFileName.IsNullOrEmpty()) return FALSE;
  1047. if((fileType == DFT_CenterSetting && ssFileName.IsStartWith("centersetting", true) && !ssFileName.IsEndWith(".ini", true))
  1048. || fileType == DFT_Ad0
  1049. ) {
  1050. if(RemoveFileA(szFilePath)) {
  1051. Dbg("%s delete suc.", szFileName);
  1052. return 1;
  1053. }
  1054. Dbg("%s delete failed %d.", szFileName, GetLastError());
  1055. return -1;
  1056. }
  1057. return 0;
  1058. }
  1059. #if defined(_MSC_VER)
  1060. void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, PWIN32_FIND_DATA pWfdata)
  1061. {
  1062. m_VideoFiles.push(new TmpFileInfo(lpFilePath,
  1063. &(pWfdata->ftLastWriteTime),
  1064. pWfdata->nFileSizeHigh, pWfdata->nFileSizeLow));
  1065. ULARGE_INTEGER uiTemp;
  1066. uiTemp.HighPart = pWfdata->nFileSizeHigh;
  1067. uiTemp.LowPart = pWfdata->nFileSizeLow;
  1068. mAllVideoFileSizeCal.QuadPart += uiTemp.QuadPart;
  1069. if (mMaxFileSize.QuadPart < uiTemp.QuadPart) {
  1070. strcpy_s(szMaxSizeFilePath, lpFilePath);
  1071. mMaxFileSize.QuadPart = uiTemp.QuadPart;
  1072. }
  1073. SyncUpdateVideoCreateDaily(&(pWfdata->ftLastWriteTime), 1);
  1074. }
  1075. void ResourceWatcherFSM::CleanMoreVideoFiles()
  1076. {
  1077. EnterCriticalSection(&g_csVideoMoreClear);
  1078. ErrorCodeEnum erroCode = Error_Succeed;
  1079. BOOL bOK = FALSE;
  1080. CSmartPointer<IConfigInfo> spConfigRun;
  1081. ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1082. if (m_VideoFiles.empty()) {
  1083. int reseved = 0;
  1084. m_bReadyFlag = IsNeedToFirstClear();
  1085. int nRes = CleanVideoFiles(reseved, m_bReadyFlag ? 1 : 0);
  1086. if (nRes - reseved == 0) {
  1087. Dbg("There are no any video files in facts.");
  1088. SetSysValAndBroadcast(0, "There are no any video files in facts.");
  1089. LeaveCriticalSection(&g_csVideoMoreClear);
  1090. return;
  1091. }
  1092. }
  1093. if (mUiRequireBytes.QuadPart == 0ui64)
  1094. {//更新记录运行时,并等待下一次的自检执行。
  1095. Dbg("empty?");
  1096. int reseved = 0;
  1097. CleanVideoFiles(reseved);
  1098. Dbg("Wait next time to execute...");
  1099. LeaveCriticalSection(&g_csVideoMoreClear);
  1100. return;
  1101. }
  1102. ULARGE_INTEGER uiSpaceRequired;
  1103. ULARGE_INTEGER uiSpaceRealRequired;
  1104. ULARGE_INTEGER uiFactor;
  1105. int CurRank = 3;
  1106. int BfRank = 0;
  1107. if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0) {
  1108. BfRank = 0;
  1109. }
  1110. if (BfRank > 0) {
  1111. ULARGE_INTEGER uiTotalBytes;
  1112. ULARGE_INTEGER uiFreeDiskBytes;
  1113. if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1114. //对比上次,剩余的可用磁盘空间更小了。
  1115. if (mUiCalibration.QuadPart >= uiFreeDiskBytes.QuadPart) {
  1116. Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
  1117. CurRank = BfRank;
  1118. }
  1119. mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
  1120. }
  1121. }
  1122. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  1123. int nEnoughLevel = 0;
  1124. do {
  1125. uiFactor.QuadPart = 0;
  1126. switch (CurRank) {
  1127. case 3:
  1128. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
  1129. break;
  1130. case 2:
  1131. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LESS_AVAILALBE_DATE_COUNT;
  1132. break;
  1133. case 1:
  1134. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * LEAST_AVAILALBE_DATE_COUNT;
  1135. break;
  1136. default:
  1137. CurRank = 3;
  1138. uiSpaceRequired.QuadPart = mUiRequireBytes.QuadPart * DEFAULT_AVAILALBE_DATE_COUNT;
  1139. }
  1140. ByteSprintf(szResult, (double)uiSpaceRequired.QuadPart);
  1141. Dbg("Required size(%d): %s", CurRank, szResult);
  1142. if (bOK = diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_uploadedVideoDirPath,
  1143. uiSpaceRequired, uiFactor, &uiSpaceRealRequired)) {
  1144. if (uiSpaceRealRequired.QuadPart == 0) {
  1145. break;
  1146. }
  1147. char displayTime[MAX_PATH] = { 0 };
  1148. FILETIME ftSavedTime;
  1149. //TODO: 暂时设置为至少保存两星期的录像文件,如果一天都不保留,那么 m_VideoFiles 要做即时更新 。2017-5-10
  1150. CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
  1151. GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
  1152. Dbg("SavedTime backtrace: %s", displayTime);
  1153. ULARGE_INTEGER uiFreeBytes;
  1154. uiFreeBytes.QuadPart = 0;
  1155. UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
  1156. BOOL bTrackBackStop = FALSE;
  1157. while (!m_VideoFiles.empty() && uiFreeBytes.QuadPart < uiSpaceRealRequired.QuadPart) {
  1158. TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
  1159. if (pCurFileInfo != NULL) {
  1160. SYSTEMTIME stUTC, stLocal;
  1161. FileTimeToSystemTime(&(pCurFileInfo->mftEditTime), &stUTC);
  1162. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  1163. if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0) {
  1164. Dbg("yet %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
  1165. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  1166. stLocal.wHour, stLocal.wMinute);
  1167. bTrackBackStop = TRUE;
  1168. break;
  1169. }
  1170. //if(TRUE)
  1171. if (DeleteFile(pCurFileInfo->msFileName.c_str()) != 0) {
  1172. ULARGE_INTEGER tmpBytes;
  1173. tmpBytes.HighPart = pCurFileInfo->mDwFileSizeHeight;
  1174. tmpBytes.LowPart = pCurFileInfo->mDwFileSizeLow;
  1175. uiFreeBytes.QuadPart += tmpBytes.QuadPart;
  1176. uDeletedCnt++;
  1177. Dbg("Delete suc: %s: %02d/%02d/%d %02d:%02d", pCurFileInfo->msFileName.c_str(),
  1178. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  1179. stLocal.wHour, stLocal.wMinute);
  1180. SyncUpdateVideoCreateDaily(&(pCurFileInfo->mftEditTime), -1);
  1181. } else {
  1182. Dbg("[DelFail] File(%s) %u", pCurFileInfo->msFileName.c_str(), GetLastError());
  1183. uFailedDeleteCnt++;
  1184. }
  1185. }
  1186. m_VideoFiles.pop();
  1187. if (pCurFileInfo != NULL) delete pCurFileInfo;
  1188. }
  1189. char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1190. char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1191. ByteSprintf(szOutput, (double)uiFreeBytes.QuadPart);
  1192. ByteSprintf(szOutput2, (double)uiSpaceRealRequired.QuadPart);
  1193. Dbg("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
  1194. CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
  1195. if (uiFreeBytes.QuadPart >= uiSpaceRealRequired.QuadPart) {
  1196. break;
  1197. }
  1198. --CurRank;
  1199. UINT uCount = 0;
  1200. for (const_map_cu_iter citer = VideoDailyRecord.cbegin();
  1201. citer != VideoDailyRecord.cend(); citer++) {
  1202. uCount += citer->second;
  1203. }
  1204. Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
  1205. } else {
  1206. LogError(Severity_Middle, Error_Unexpect, 0, "IsNeedToDoClearJobEx invoked failed !");
  1207. LeaveCriticalSection(&g_csVideoMoreClear);
  1208. return;
  1209. }
  1210. } while (CurRank > 0);
  1211. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
  1212. if (CurRank < 3) {
  1213. ULARGE_INTEGER uiTotalBytes;
  1214. ULARGE_INTEGER uiFreeDiskBytes;
  1215. if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1216. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  1217. ByteSprintf(szResult, (double)uiTotalBytes.QuadPart);
  1218. ByteSprintf(szResult2, (double)uiFreeDiskBytes.QuadPart);
  1219. double dFreeRate = (uiFreeDiskBytes.QuadPart * kConversion[3]) / (uiTotalBytes.QuadPart * kConversion[3]);
  1220. sprintf_s(szResult3, "[Disk# %c:\\] total: %s, free: %s, rate: %.1lf%%.",
  1221. m_uploadedVideoDirPath[0], szResult, szResult2, dFreeRate * 100);
  1222. mUiCalibration.QuadPart = uiFreeDiskBytes.QuadPart;
  1223. } else {
  1224. strcpy_s(szResult3, "It's not enough disk space for recording video !");
  1225. }
  1226. if (CurRank == 0) {
  1227. CurRank = 4;
  1228. }
  1229. } else {
  1230. strcpy_s(szResult3, "Disk space is enough for recording.");
  1231. }
  1232. if (BfRank != CurRank) {
  1233. erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
  1234. }
  1235. SetSysValAndBroadcast(CurRank, szResult3);
  1236. LeaveCriticalSection(&g_csVideoMoreClear);
  1237. return;
  1238. }
  1239. #else
  1240. void ResourceWatcherFSM::RecordVideoFileInfomation(LPCTSTR lpFilePath, struct stat* pWfdata)
  1241. {
  1242. m_VideoFiles.push(new TmpFileInfo(lpFilePath, pWfdata->st_mtime , pWfdata->st_size));
  1243. mAllVideoFileSizeCal += pWfdata->st_size;
  1244. if (mMaxFileSize < pWfdata->st_size) {
  1245. strcpy(szMaxSizeFilePath, lpFilePath);
  1246. mMaxFileSize = pWfdata->st_size;
  1247. }
  1248. SyncUpdateVideoCreateDaily(&pWfdata->st_mtime, 1);
  1249. }
  1250. void ResourceWatcherFSM::CleanMoreVideoFiles()
  1251. {
  1252. EnterCriticalSection(&g_csVideoMoreClear);
  1253. ErrorCodeEnum erroCode = Error_Succeed;
  1254. BOOL bOK = FALSE;
  1255. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE * 2] = { 0 };
  1256. CSmartPointer<IConfigInfo> spConfigRun;
  1257. ErrorCodeEnum ecRunCfg = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  1258. if (m_VideoFiles.empty() || mUiRequireBytes == 0) {
  1259. int reseved = 0;
  1260. int nRes = CleanVideoFiles(reseved, IsNeedToFirstClear() ? 1 : 0);
  1261. if (nRes - reseved == 0) {
  1262. Dbg("There are no any video files in facts.");
  1263. //SetSysValAndBroadcast(0, "There are no any video files in facts.");
  1264. LeaveCriticalSection(&g_csVideoMoreClear);
  1265. return;
  1266. }
  1267. }
  1268. int CurRank = 3; //default
  1269. int BfRank = 0;
  1270. if (spConfigRun->ReadConfigValueInt("Video", "RequiredRank", BfRank) != Error_Succeed || BfRank < 0) {
  1271. BfRank = 0;
  1272. }
  1273. if (BfRank > 0) {
  1274. unsigned long long uiTotalBytes;
  1275. unsigned long long uiFreeDiskBytes;
  1276. if (!DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1277. LeaveCriticalSection(&g_csVideoMoreClear);
  1278. return;
  1279. }
  1280. //对比上次,剩余的可用磁盘空间更小了。
  1281. if (mUiCalibration >= uiFreeDiskBytes) {
  1282. Dbg("Previous Set CurRank from %d to %d.", CurRank, BfRank);
  1283. CurRank = BfRank == 4 ? 1: BfRank;
  1284. }
  1285. mUiCalibration = uiFreeDiskBytes;
  1286. }
  1287. const int InitialRank = CurRank;
  1288. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  1289. int nEnoughLevel = 0;
  1290. unsigned long long uiFactor;
  1291. char displayTime[MAX_PATH] = { 0 };
  1292. time_t ftSavedTime;
  1293. CalculateBackTime(&ftSavedTime, m_nMinSavedDay);
  1294. GetTimeFormatStr(displayTime, MAX_PATH, &ftSavedTime);
  1295. Dbg("It's SavedTime backtrace: %s", displayTime);
  1296. do {
  1297. uiFactor = DEFAULT_AVAILALBE_DATE_COUNT; // 7天
  1298. if (CurRank == 2) uiFactor = LESS_AVAILALBE_DATE_COUNT; // 3天
  1299. else if (CurRank == 1) uiFactor = LEAST_AVAILALBE_DATE_COUNT; // 1天
  1300. const unsigned long long uiSpaceRequired = mUiRequireBytes * uiFactor;
  1301. ByteSprintf(szResult, (double)uiSpaceRequired);
  1302. Dbg("Required free disk size: %s, current rank: %d", szResult, CurRank);
  1303. unsigned long long uiMoreSpaceRealRequired(0);
  1304. unsigned long long uiAdjustment(0);
  1305. if (diskInfo.IsNeedToDoClearJobEx((LPCTSTR)m_uploadedVideoDirPath, uiSpaceRequired, uiAdjustment, &uiMoreSpaceRealRequired)
  1306. && uiMoreSpaceRealRequired) {
  1307. unsigned long long uiNewFreeBytes(0);
  1308. UINT uDeletedCnt = 0, uFailedDeleteCnt = 0;
  1309. BOOL bTrackBackStop = FALSE;
  1310. Dbg("the more space required: %llu.", uiMoreSpaceRealRequired);
  1311. while (!m_VideoFiles.empty() && uiNewFreeBytes < uiMoreSpaceRealRequired) {
  1312. TmpFileInfo* pCurFileInfo = m_VideoFiles.top();
  1313. if (pCurFileInfo != NULL) {
  1314. GetTimeFormatStr(displayTime, MAX_PATH, &(pCurFileInfo->mftEditTime));
  1315. if (CompareVideoFileTime(&ftSavedTime, &(pCurFileInfo->mftEditTime)) < 0) {
  1316. Dbg("stop at %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
  1317. bTrackBackStop = TRUE;
  1318. break;
  1319. }
  1320. if (RemoveFileA(pCurFileInfo->msFileName.c_str()) != 0) {
  1321. uiNewFreeBytes += pCurFileInfo->ftSize;
  1322. uDeletedCnt++;
  1323. Dbg("Delete suc: %s: %s", pCurFileInfo->msFileName.c_str(), displayTime);
  1324. SyncUpdateVideoCreateDaily(&(pCurFileInfo->mftEditTime), -1);
  1325. } else {
  1326. Dbg("[DelFail] File(%s) %d", pCurFileInfo->msFileName.c_str(), errno);
  1327. uFailedDeleteCnt++;
  1328. }
  1329. }
  1330. m_VideoFiles.pop();
  1331. if (pCurFileInfo != NULL) delete pCurFileInfo;
  1332. }
  1333. char szOutput[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1334. char szOutput2[DEFAULT_OUTPUT_FORMAT_SIZE] = { 0 };
  1335. ByteSprintf(szOutput, (double)uiNewFreeBytes);
  1336. ByteSprintf(szOutput2, (double)uiMoreSpaceRealRequired);
  1337. Dbg("Result(Rank#%d): Succeed deleted<%d>, Failed deleted<%d>, Deleted Size<%s> Real Required Size<%s>",
  1338. CurRank, uDeletedCnt, uFailedDeleteCnt, szOutput, szOutput2);
  1339. if (uiNewFreeBytes >= uiMoreSpaceRealRequired) {
  1340. break;
  1341. } else {
  1342. --CurRank;
  1343. }
  1344. #ifdef WITH_DEBUG
  1345. UINT uCount = 0;
  1346. for (const_map_cu_iter citer = VideoDailyRecord.cbegin(); citer != VideoDailyRecord.cend(); citer++) { uCount += citer->second; }
  1347. Dbg("FileCount(%d)(%d)", uCount, m_VideoFiles.size());
  1348. #endif
  1349. } else if(InitialRank > CurRank) {
  1350. break;
  1351. } else {
  1352. LeaveCriticalSection(&g_csVideoMoreClear);
  1353. return;
  1354. }
  1355. } while (CurRank > 0);
  1356. if (CurRank < 3) {
  1357. unsigned long long uiTotalBytes;
  1358. unsigned long long uiFreeDiskBytes;
  1359. if (DiskInfo::GetDiskSpace((LPCTSTR)m_uploadedVideoDirPath, uiTotalBytes, uiFreeDiskBytes)) {
  1360. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  1361. ByteSprintf(szResult, (double)uiTotalBytes);
  1362. ByteSprintf(szResult2, (double)uiFreeDiskBytes);
  1363. double dFreeRate = (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
  1364. sprintf(szResult3, "[Disk# %s] total: %s, free: %s, rate: %.1lf%%.",
  1365. m_uploadedVideoDirPath.GetData(), szResult, szResult2, dFreeRate * 100);
  1366. mUiCalibration = uiFreeDiskBytes;
  1367. } else {
  1368. strcpy(szResult3, "It's not enough disk space for recording video !");
  1369. }
  1370. } else {
  1371. strcpy(szResult3, "Disk space is enough for recording.");
  1372. }
  1373. if (CurRank == 0) { CurRank = 4; }
  1374. if (BfRank != CurRank) {
  1375. erroCode = spConfigRun->WriteConfigValueInt("Video", "RequiredRank", CurRank);
  1376. }
  1377. SetSysValAndBroadcast(CurRank, szResult3);
  1378. LeaveCriticalSection(&g_csVideoMoreClear);
  1379. return;
  1380. }
  1381. #endif //_MSC_VER
  1382. bool ResourceWatcherFSM::IsNeedToFirstClear()
  1383. {
  1384. int nLastTaskTime(0);
  1385. CSmartPointer<IConfigInfo> spRunConfig;
  1386. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  1387. spRunConfig->ReadConfigValueInt("LastClearTime", "Video", nLastTaskTime);
  1388. return !IsTodayDone(nLastTaskTime);
  1389. }
  1390. int ResourceWatcherFSM::ProcessFileDelete(LPCTSTR lpszPath, int& nDelSucCnt, int& nDelFailedCnt)
  1391. {
  1392. int fileCnt = 0;
  1393. int fileLength = strlen(lpszPath);
  1394. char* searchFilePath = new char[MAX_PATH];
  1395. char* tempFilePath = new char[MAX_PATH];
  1396. if (searchFilePath == NULL || tempFilePath == NULL) {
  1397. if (searchFilePath) delete[] searchFilePath;
  1398. if (tempFilePath) delete[] tempFilePath;
  1399. return fileCnt;
  1400. }
  1401. ZeroMemory(searchFilePath, MAX_PATH);
  1402. ZeroMemory(tempFilePath, MAX_PATH);
  1403. #if defined(_MSC_VER)
  1404. WIN32_FIND_DATA wfd;
  1405. HANDLE hFind;
  1406. hFind = FindFirstFile(lpszPath, &wfd);
  1407. if (hFind == INVALID_HANDLE_VALUE) {
  1408. Dbg("FindFirstFile failed GLE = %u.", GetLastError());
  1409. if (searchFilePath) delete[] searchFilePath;
  1410. if (tempFilePath) delete[] tempFilePath;
  1411. return 0;
  1412. }
  1413. do {
  1414. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  1415. if (wfd.cFileName[0] != '.') {
  1416. strcpy_s(tempFilePath, MAX_PATH, lpszPath);
  1417. tempFilePath[fileLength - 1] = '\0';
  1418. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH) {
  1419. Dbg("filePath is too long for current.");
  1420. } else {
  1421. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
  1422. CSimpleStringA tmpPath = tempFilePath;
  1423. strcat_s(tempFilePath, MAX_PATH, "\\*");
  1424. int tDelSucCnt = 0, tDelFailedCnt = 0;
  1425. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
  1426. if (tDelFailedCnt == 0 && !RemoveDirectoryA(tmpPath)) {
  1427. Dbg("RemoveDirectoryA(%s) failed, GLE = %u.", (LPCTSTR)tmpPath, GetLastError());
  1428. nDelFailedCnt++;
  1429. }
  1430. nDelFailedCnt += tDelFailedCnt;
  1431. nDelSucCnt += tDelSucCnt;
  1432. }
  1433. }
  1434. } else {
  1435. strcpy_s(searchFilePath, MAX_PATH, lpszPath);
  1436. searchFilePath[fileLength - 1] = '\0';
  1437. strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
  1438. if (DeleteFile(searchFilePath) != 0) {
  1439. nDelSucCnt++;
  1440. Dbg("Delete [%s] suc.", wfd.cFileName);
  1441. } else {
  1442. nDelFailedCnt++;
  1443. Dbg("Delete [%s] failed, GLE = %u.", wfd.cFileName, GetLastError());
  1444. }
  1445. fileCnt++;
  1446. }
  1447. } while (FindNextFileA(hFind, &wfd));
  1448. FindClose(hFind);
  1449. #else
  1450. struct stat st;
  1451. if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
  1452. if (searchFilePath) delete[] searchFilePath;
  1453. if (tempFilePath) delete[] tempFilePath;
  1454. Dbg("stat failed or is not dir.");
  1455. return fileCnt;
  1456. }
  1457. DIR* d = opendir(lpszPath);
  1458. if (!d) {
  1459. if (searchFilePath) delete[] searchFilePath;
  1460. if (tempFilePath) delete[] tempFilePath;
  1461. Dbg("opendir failed: %d", errno);
  1462. return fileCnt;
  1463. }
  1464. struct dirent* dp = NULL;
  1465. while ((dp = readdir(d)) != NULL) {
  1466. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1467. continue;
  1468. }
  1469. strcpy(tempFilePath, lpszPath);
  1470. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1471. Dbg("filePath is too long for current.");
  1472. continue;
  1473. }
  1474. strcat(tempFilePath, "/");
  1475. strcat(tempFilePath, dp->d_name);
  1476. stat(tempFilePath, &st);
  1477. bool isdir = !!(S_ISDIR(st.st_mode));
  1478. if (isdir) {
  1479. int tDelSucCnt = 0, tDelFailedCnt = 0;
  1480. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt);
  1481. if (tDelFailedCnt == 0 && rmdir(tempFilePath) != 0) {
  1482. Dbg("rmdir(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno);
  1483. nDelFailedCnt++;
  1484. }
  1485. nDelFailedCnt += tDelFailedCnt;
  1486. nDelSucCnt += tDelSucCnt;
  1487. } else {
  1488. if (RemoveFileA(tempFilePath)) {
  1489. nDelSucCnt++;
  1490. Dbg("Delete [%s] suc.", dp->d_name);
  1491. } else {
  1492. nDelFailedCnt++;
  1493. Dbg("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno);
  1494. }
  1495. fileCnt++;
  1496. }
  1497. }
  1498. closedir(d);
  1499. #endif //_MSC_VER
  1500. if(searchFilePath) delete[] searchFilePath;
  1501. if(tempFilePath) delete[] tempFilePath;
  1502. searchFilePath = NULL;
  1503. tempFilePath = NULL;
  1504. return fileCnt;
  1505. }
  1506. BOOL ResourceWatcherFSM::DeleteVersionPackage()
  1507. {
  1508. LOG_FUNCTION();
  1509. BOOL bRet = FALSE;
  1510. ErrorCodeEnum erroCode = Error_Succeed;
  1511. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  1512. CSmartPointer<IConfigInfo> spConfigRun;
  1513. CSystemStaticInfo info;
  1514. if(pFunc->GetSystemStaticInfo(info) != Error_Succeed) {
  1515. LogError(Severity_Middle, erroCode, 0, "Get system static info error");
  1516. return FALSE;
  1517. }
  1518. Dbg("Current version: %s", (LPCTSTR)info.InstallVersion.ToString());
  1519. int nLastTaskTime = 0;
  1520. int nLstFlag = 0;
  1521. UINT64 utVersion = 0;
  1522. pFunc->OpenConfig(Config_Run, spConfigRun);
  1523. spConfigRun->ReadConfigValueHexInt("VersionClear", "OptVer", utVersion);
  1524. spConfigRun->ReadConfigValueInt("VersionClear", "LastCondi", nLstFlag); //last times is failed or not? failed:true
  1525. spConfigRun->ReadConfigValueInt("VersionClear", "LastTime", nLastTaskTime);
  1526. CVersion optVer(utVersion);
  1527. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  1528. Dbg("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
  1529. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  1530. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  1531. (LPCTSTR)optVer.ToString(), nLstFlag);
  1532. //判断是否需要被清理
  1533. if (optVer.IsValid() && optVer == info.InstallVersion && !nLstFlag) {
  1534. Dbg("VersionPackage cleaning has been done before.");
  1535. return TRUE;
  1536. }
  1537. vector<CInstallInfoEx> intallInfoVects;
  1538. CVersion lastVer = info.PreviousInstallVersion;
  1539. while (lastVer.IsValid())
  1540. {
  1541. CInstallInfo lastVerInfo = {};
  1542. erroCode = pFunc->GetInstallInfo(lastVer, lastVerInfo);
  1543. if (erroCode != Error_Succeed) {
  1544. break;
  1545. }
  1546. intallInfoVects.push_back(CInstallInfoEx(lastVerInfo));
  1547. lastVer = lastVerInfo.PreviousInstallVersion;
  1548. }
  1549. int nPackCount = intallInfoVects.size();
  1550. Dbg("Install Package's count: %d", nPackCount);
  1551. bool bFailFlag = false;
  1552. int nDelVersionCnt = 0;
  1553. if(nPackCount != 0) {
  1554. int nSavedCount = 0;
  1555. sort(intallInfoVects.begin(), intallInfoVects.end());
  1556. vector<CInstallInfoEx>::iterator iter = intallInfoVects.begin();
  1557. while(iter != intallInfoVects.end())
  1558. {
  1559. Dbg("InstallPackage Info: %s, SwithOverDate: %s", (LPCTSTR)iter->InstallVersion.ToString(), (LPCTSTR)iter->tmSwithOverDate.ToTimeString());
  1560. if(++nSavedCount <= DEFAULT_VERSION_SAVED_COUNT) {
  1561. Dbg("Save above version");
  1562. iter++;
  1563. continue;
  1564. }
  1565. if(!DeleteSpecificeVersionDir(iter->InstallVersion))
  1566. bFailFlag = true;
  1567. else
  1568. nDelVersionCnt++;
  1569. iter++;
  1570. }
  1571. }
  1572. nLstFlag = bFailFlag ? 1 : 0;
  1573. spConfigRun->WriteConfigValueHexInt("VersionClear", "OptVer", info.InstallVersion.GetVersion64());
  1574. spConfigRun->WriteConfigValueInt("VersionClear", "LastCondi", nLstFlag);
  1575. spConfigRun->WriteConfigValue("VersionClear", "LastTime",
  1576. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  1577. return TRUE;
  1578. }
  1579. BOOL ResourceWatcherFSM::DeleteSpecificeVersionDir(CVersion version)
  1580. {
  1581. ErrorCodeEnum erroCode = Error_Unexpect;
  1582. CSimpleStringA strPath;
  1583. if (GetEntityBase()->GetFunction()->GetPath("RootVer", strPath) != Error_Succeed)
  1584. return FALSE;
  1585. strPath = strPath + SPLIT_SLASH_STR + version.ToString();
  1586. if (!ExistsDirA(strPath)) {
  1587. Dbg("Directory(%s) Not Existed, Maybe delete before !!", strPath.GetData());
  1588. return TRUE;
  1589. }
  1590. CSimpleStringA tmpDirPath = strPath;
  1591. #if defined(_MSC_VER)
  1592. tmpDirPath += "\\*";
  1593. #endif //_MSC_VER
  1594. Dbg("operating version path: [%s][%s]", (LPCTSTR)tmpDirPath, (LPCTSTR)strPath);
  1595. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  1596. nFileCount = ProcessFileDelete((LPCTSTR)tmpDirPath, nDelSuc, nDelFail);
  1597. Dbg("Process result(%s): count(%d), suc(%d), failed(%d).", tmpDirPath.GetData(), nFileCount, nDelSuc, nDelFail);
  1598. #if defined(_MSC_VER)
  1599. if (nDelFail != 0 || !RemoveDirectoryA(tmpDirPath)) {
  1600. Dbg("Unexpect condition happen: (%d)(%u).", nDelFail, GetLastError());
  1601. #else
  1602. if (nDelFail != 0 || rmdir(tmpDirPath) != 0) {
  1603. Dbg("Unexpect condition happen: (%d)", nDelFail);
  1604. #endif //_MSC_VER
  1605. return FALSE;
  1606. }
  1607. return TRUE;
  1608. }
  1609. #if defined(_MSC_VER)
  1610. int ResourceWatcherFSM::CalculateAllVideoSize(LPCTSTR lpszPath, PULARGE_INTEGER puliSpaceBytes)
  1611. {
  1612. int fileCnt = 0;
  1613. int fileLength = strlen(lpszPath);
  1614. char* searchFilePath = new char[MAX_PATH];
  1615. char* tempFilePath = new char[MAX_PATH];
  1616. if (searchFilePath == NULL || tempFilePath == NULL) {
  1617. if (searchFilePath) delete[] searchFilePath;
  1618. if (tempFilePath) delete[] tempFilePath;
  1619. return fileCnt;
  1620. }
  1621. ZeroMemory(searchFilePath, MAX_PATH);
  1622. ZeroMemory(tempFilePath, MAX_PATH);
  1623. WIN32_FIND_DATA wfd;
  1624. HANDLE hFind;
  1625. hFind = FindFirstFile(lpszPath, &wfd);
  1626. if (hFind == INVALID_HANDLE_VALUE) {
  1627. Dbg("FindFirstFile failed GLE = %u.", GetLastError());
  1628. if (searchFilePath) delete[] searchFilePath;
  1629. if (tempFilePath) delete[] tempFilePath;
  1630. return 0;
  1631. }
  1632. do {
  1633. if ((wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
  1634. if (wfd.cFileName[0] != '.') {
  1635. strcpy_s(tempFilePath, MAX_PATH, lpszPath);
  1636. tempFilePath[fileLength - 1] = '\0';
  1637. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH) {
  1638. Dbg("filePath is too long for current.");
  1639. } else {
  1640. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName);
  1641. strcat_s(tempFilePath, MAX_PATH, "\\*");
  1642. fileCnt += CalculateAllVideoSize((LPCTSTR)tempFilePath, puliSpaceBytes);
  1643. }
  1644. }
  1645. } else {
  1646. strcpy_s(searchFilePath, MAX_PATH, lpszPath);
  1647. searchFilePath[fileLength - 1] = '\0';
  1648. strcat_s(searchFilePath, MAX_PATH, wfd.cFileName);
  1649. ULARGE_INTEGER uiTemp;
  1650. uiTemp.HighPart = wfd.nFileSizeHigh;
  1651. uiTemp.LowPart = wfd.nFileSizeLow;
  1652. puliSpaceBytes->QuadPart += uiTemp.QuadPart;
  1653. SyncUpdateVideoCreateDaily(&wfd.ftLastWriteTime, 1);
  1654. fileCnt++;
  1655. }
  1656. } while (FindNextFileA(hFind, &wfd));
  1657. FindClose(hFind);
  1658. if (searchFilePath) delete[] searchFilePath;
  1659. if (tempFilePath) delete[] tempFilePath;
  1660. return fileCnt;
  1661. }
  1662. #else
  1663. int ResourceWatcherFSM::CalculateAllVideoSize(LPCTSTR lpszPath, unsigned long long* puliSpaceBytes)
  1664. {
  1665. int fileCnt = 0;
  1666. int fileLength = strlen(lpszPath);
  1667. char* searchFilePath = new char[MAX_PATH];
  1668. char* tempFilePath = new char[MAX_PATH];
  1669. if (searchFilePath == NULL || tempFilePath == NULL) {
  1670. if (searchFilePath) delete[] searchFilePath;
  1671. if (tempFilePath) delete[] tempFilePath;
  1672. return fileCnt;
  1673. }
  1674. ZeroMemory(searchFilePath, MAX_PATH);
  1675. ZeroMemory(tempFilePath, MAX_PATH);
  1676. struct stat st;
  1677. if (stat(lpszPath, &st) < 0 || !S_ISDIR(st.st_mode)) {
  1678. if (searchFilePath) delete[] searchFilePath;
  1679. if (tempFilePath) delete[] tempFilePath;
  1680. return fileCnt;
  1681. }
  1682. DIR* d = opendir(lpszPath);
  1683. if (!d) {
  1684. if (searchFilePath) delete[] searchFilePath;
  1685. if (tempFilePath) delete[] tempFilePath;
  1686. return fileCnt;
  1687. }
  1688. struct dirent* dp = NULL;
  1689. while ((dp = readdir(d)) != NULL) {
  1690. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  1691. continue;
  1692. }
  1693. strcpy(tempFilePath, lpszPath);
  1694. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  1695. Dbg("filePath is too long for current.");
  1696. continue;
  1697. }
  1698. strcat(tempFilePath, "/");
  1699. strcat(tempFilePath, dp->d_name);
  1700. stat(tempFilePath, &st);
  1701. const bool isdir = !!(S_ISDIR(st.st_mode));
  1702. if (isdir) {
  1703. fileCnt += CalculateAllVideoSize((LPCTSTR)tempFilePath, puliSpaceBytes);
  1704. } else {
  1705. *puliSpaceBytes += st.st_size;
  1706. SyncUpdateVideoCreateDaily(&st.st_mtime, 1);
  1707. fileCnt++;
  1708. }
  1709. }
  1710. closedir(d);
  1711. if (searchFilePath) delete[] searchFilePath;
  1712. if (tempFilePath) delete[] tempFilePath;
  1713. return fileCnt;
  1714. }
  1715. #endif //_MSC_VER
  1716. void ResourceWatcherFSM::SelfTest(EntityTestEnum eTestType,
  1717. CSmartPointer<ITransactionContext> pTransactionContext)
  1718. {
  1719. static uint32_t times = 0;
  1720. pTransactionContext->SendAnswer(Error_Succeed);
  1721. times++;
  1722. if(m_bVideoClearReady && times > 60 * 2) { //2 hour per times
  1723. times = 0;
  1724. PostEventFIFO(new FSMEvent(USER_EVT_CLEAR_VIDEOFILE_ENHANCE));
  1725. }
  1726. }
  1727. void ResourceWatcherFSM::SetSysValAndBroadcast(DWORD dwVal, LPCTSTR lpszMessage)
  1728. {
  1729. static DWORD dwOldVal = (DWORD)-1;
  1730. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  1731. CSimpleStringA csVPStatus = VIDEO_SPACE_UNKNOWN;
  1732. CSimpleStringA csNewVPSatus = VIDEO_SPACE_UNKNOWN;
  1733. spFunction->GetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csVPStatus);
  1734. if(dwVal == 4)
  1735. {
  1736. csNewVPSatus = VIDEO_SPACE_INSUFF_FATAL;
  1737. LogError(Severity_High, Error_TooSmallBuffer, LOG_ERR_RES_VIDEO_INSUFFICIENT, lpszMessage);
  1738. }
  1739. else if(dwVal == 2)
  1740. {
  1741. csNewVPSatus = VIDEO_SPACE_INSUFF_LITTLE;
  1742. if(dwVal != dwOldVal)
  1743. LogWarn(Severity_Middle, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
  1744. }
  1745. else if(dwVal == 1)
  1746. {
  1747. csNewVPSatus = VIDEO_SPACE_INSUFF_LESS;
  1748. if(dwVal != dwOldVal)
  1749. LogWarn(Severity_Low, Error_TooSmallBuffer, LOG_WARN_RES_VIDEO_INSUFFICIENT, lpszMessage);
  1750. }
  1751. else if(dwVal == 3)
  1752. {
  1753. csNewVPSatus = VIDEO_SPACE_SUFFICIENT;
  1754. if(dwVal != dwOldVal)
  1755. LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
  1756. }
  1757. else if(dwVal == 0)
  1758. {
  1759. if(dwVal != dwOldVal)
  1760. LogEvent(Severity_High, LOG_EVT_RES_VIDEO_SUFFICIENT, lpszMessage);
  1761. }
  1762. else
  1763. {
  1764. Dbg("Unknow dwVal: %d", dwVal);
  1765. }
  1766. if(csNewVPSatus != csVPStatus)
  1767. {
  1768. ErrorCodeEnum eRet = spFunction->SetSysVar(SYSVAR_DISKSTATEUS_FOR_VIDEO, csNewVPSatus);
  1769. Dbg("SetSysVar(%s) from '%s' to '%s' returned %d",
  1770. SYSVAR_DISKSTATEUS_FOR_VIDEO
  1771. , (LPCTSTR)csVPStatus
  1772. , (LPCTSTR)csNewVPSatus
  1773. , eRet);
  1774. }
  1775. dwOldVal = dwVal;
  1776. }
  1777. BOOL ResourceWatcherFSM::InitialDirectoryEntity(LPCTSTR lpszPath, DWORD& dwFileCnt, const DWORD dwFilterAttributes)
  1778. {
  1779. LOG_FUNCTION();
  1780. if(lpszPath == NULL) {
  1781. SetLastError(ERROR_INVALID_PARAMETER);
  1782. LogWarn(Severity_Middle, Error_Param, ERROR_INVALID_PARAMETER, "Null file path !");
  1783. return FALSE;
  1784. }
  1785. #if defined(_MSC_VER)
  1786. HANDLE hFile = CreateFileA(
  1787. lpszPath,
  1788. GENERIC_READ,
  1789. FILE_SHARE_READ,
  1790. NULL,
  1791. OPEN_EXISTING,
  1792. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
  1793. NULL);
  1794. if (hFile == INVALID_HANDLE_VALUE) {
  1795. Dbg("CreateFileA(%s) failed", lpszPath);
  1796. return FALSE;
  1797. }
  1798. #endif //_MSC_VER
  1799. m_FileEntry.SubFiles.Clear();
  1800. m_FileEntry.FileNamesBuffer.Clear();
  1801. m_FileEntry.Current.Clear();
  1802. DWORD dwLocate;
  1803. Append(m_FileEntry.FileNamesBuffer, (PBYTE)lpszPath, strlen(lpszPath), dwLocate);
  1804. m_FileEntry.Current.mNameOffset = dwLocate;
  1805. m_FileEntry.Current.mNameLength = strlen(lpszPath);
  1806. #if defined(_MSC_VER)
  1807. GetFileTime(hFile, (LPFILETIME)&m_FileEntry.Current.mftCreate,
  1808. (LPFILETIME)&m_FileEntry.Current.mftAccess, (LPFILETIME)&m_FileEntry.Current.mftModified);
  1809. CloseHandle(hFile);
  1810. hFile = NULL;
  1811. m_FileEntry.Current.mAttributes = GetFileAttributesA(lpszPath);
  1812. m_FileEntry.Current.mFileSize = 0;
  1813. #else
  1814. struct stat st;
  1815. if (stat(lpszPath, &st) < 0) {
  1816. Dbg("stat %s failed.", lpszPath);
  1817. return FALSE;
  1818. }
  1819. //GetFileTime
  1820. m_FileEntry.Current.mftCreate = st.st_ctime;
  1821. m_FileEntry.Current.mftAccess = st.st_atime;
  1822. m_FileEntry.Current.mftModified = st.st_mtime;
  1823. m_FileEntry.Current.mAttributes = 0;
  1824. //GetFileAttributesA
  1825. if (S_ISDIR(st.st_mode)) {
  1826. m_FileEntry.Current.mFileSize = 0;
  1827. m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_DIRECTORY;
  1828. } else {
  1829. m_FileEntry.Current.mFileSize = st.st_size;
  1830. }
  1831. if (m_FileEntry.Current.mAttributes == 0)
  1832. m_FileEntry.Current.mAttributes = FILE_ATTRIBUTE_ARCHIVE;
  1833. if (!(st.st_mode & S_IWUSR))
  1834. m_FileEntry.Current.mAttributes |= FILE_ATTRIBUTE_READONLY;
  1835. #endif //_MSC_VER
  1836. DWORD dwDir = 0, dwFile = 0;
  1837. GetSubFileInfors(&m_FileEntry, dwDir, dwFile, dwFilterAttributes);
  1838. Dbg("Flag: dwDir:%u, dwFile: %u", dwDir, dwFile);
  1839. DisplayFileEntities(&m_FileEntry);
  1840. dwFileCnt = dwDir + dwFile;
  1841. #if defined(RVC_OS_LINUX)
  1842. m_FileEntry.Current.mFileSize = dwFileCnt;
  1843. #endif //RVC_OS_LINUX
  1844. return TRUE;
  1845. }
  1846. DWORD ResourceWatcherFSM::InitialVolumes()
  1847. {
  1848. LOG_FUNCTION();
  1849. UINT uCount = 0;
  1850. #if defined(RVC_OS_WIN)
  1851. /*获取磁盘信息,该坐标下的内容作为是否遍历的标识*/
  1852. if (!sBDiskValStatus[MAX_VOLUME_COUNT]) {
  1853. CHAR szDrivers[BUFSIZE] = { 0 };
  1854. CHAR szVolumeName[MAX_PATH] = { 0 };
  1855. CHAR szFileSysName[MAX_PATH] = { 0 };
  1856. BOOL bRet = GetLogicalDriveStringsA(BUFSIZE - 1, szDrivers);
  1857. if (bRet) {
  1858. Dbg("szDrivers: %s", szDrivers);
  1859. for (CHAR* pTemp = szDrivers; *pTemp != '\0'; pTemp += 4) {
  1860. if (*pTemp >= 'a' && *pTemp <= 'z') *pTemp -= 32;
  1861. const int nDriNum = *pTemp - 'A';
  1862. if (DRIVE_FIXED == GetDriveType(pTemp)) {
  1863. DWORD dwMaxCompLen, dwFileSystemFlags;
  1864. bRet = GetVolumeInformation(pTemp, szVolumeName, MAX_PATH, NULL,
  1865. &dwMaxCompLen, &dwFileSystemFlags, szFileSysName, MAX_PATH);
  1866. sBDiskValStatus[nDriNum] = TRUE;
  1867. uCount++;
  1868. } else {
  1869. sBDiskValStatus[nDriNum] = FALSE;
  1870. }
  1871. }
  1872. }
  1873. if (uCount > 0) {
  1874. sBDiskValStatus[MAX_VOLUME_COUNT] = TRUE;
  1875. }
  1876. }
  1877. m_FileEntry.SubFiles.Clear();
  1878. m_FileEntry.FileNamesBuffer.Clear();
  1879. m_FileEntry.Current.Clear();
  1880. uCount = 0;
  1881. ULARGE_INTEGER uiTotalBytes, uiTotalFreeBytes;
  1882. if (sBDiskValStatus[MAX_VOLUME_COUNT]) {
  1883. m_FileEntry.Current.mLevel = -2; //mark parent of volume -2-level
  1884. char szVolume[8] = { 0 };
  1885. for (int i = 0; i < MAX_VOLUME_COUNT; ++i) {
  1886. if (sBDiskValStatus[i]) {
  1887. szVolume[0] = i + 'A';
  1888. szVolume[1] = ':';
  1889. szVolume[2] = '\0';
  1890. CSimpleFileComponent volume;
  1891. if (DiskInfo::GetDiskSpace(szVolume, uiTotalBytes, uiTotalFreeBytes)) {
  1892. volume.mFileSize = uiTotalFreeBytes.QuadPart;
  1893. }
  1894. volume.mLevel = 0;
  1895. volume.mNameLength = strlen(szVolume);
  1896. Append(m_FileEntry.FileNamesBuffer, (PBYTE)szVolume, volume.mNameLength, volume.mNameOffset);
  1897. volume.mAttributes = 0;
  1898. m_FileEntry.SubFiles.Append(&volume, 0, 1);
  1899. uCount++;
  1900. }
  1901. }
  1902. }
  1903. DisplayFileEntities(&m_FileEntry);
  1904. #else
  1905. #endif //RVC_OS_WIN
  1906. return uCount;
  1907. }
  1908. DWORD ResourceWatcherFSM::ProcessFileOperation(
  1909. const SpReqAnsContext<ResourceWatcherService_OperateFile_Req, ResourceWatcherService_OperateFile_Ans>::Pointer& ctx)
  1910. {
  1911. if (ctx == NULL) {
  1912. return 0;
  1913. }
  1914. ResourceWatcherService_OperateFile_Req& req = ctx->Req;
  1915. ResourceWatcherService_OperateFile_Ans& ans = ctx->Ans;
  1916. {
  1917. ans.header = "";
  1918. ans.attachment1 = 0;
  1919. ans.attachment2 = "";
  1920. ans.fileSize = 0ULL;
  1921. ans.ftCreate = 0ULL;
  1922. ans.ftModified = 0ULL;
  1923. ans.ftAccess = 0ULL;
  1924. ans.fileAttribute = 0U;
  1925. ans.count = 0;
  1926. }
  1927. CSimpleStringA strCurrent(true);
  1928. size_t nCurLen = req.current.GetLength();
  1929. Dbg("size of current dir: %d", nCurLen);
  1930. if(!req.current.IsNullOrEmpty()) {
  1931. CSimpleStringA strTemp = req.current.Trim();
  1932. size_t len = req.current.GetLength();
  1933. while(len > 0 && (strTemp[len-1] == '\\' || strTemp[len-1] == '/')) {
  1934. strTemp[len-1] = '\0';
  1935. len--;
  1936. }
  1937. if(len > 0) {
  1938. strCurrent = strTemp.Trim();
  1939. nCurLen = strCurrent.GetLength();
  1940. LOG_ASSERT(len == nCurLen);
  1941. Dbg("size of strCurrent: %d", nCurLen);
  1942. }
  1943. }
  1944. BOOL bCurNull = strCurrent.IsNullOrEmpty();
  1945. if(!bCurNull)
  1946. {
  1947. int nRes = FilterFilePathAhead(strCurrent, req.mode);
  1948. if(nRes != 0) {
  1949. ans.result = OPT_FILE_RES_FAILED;
  1950. CSimpleStringA strTxt;
  1951. switch(nRes)
  1952. {
  1953. case -1:
  1954. case -2:
  1955. strTxt = "文件路径参数错误。";
  1956. break;
  1957. case -3:
  1958. strTxt = "终端指定磁盘不存在。";
  1959. break;
  1960. case 1:
  1961. strTxt = "操作非法:不允许删除盘符。";
  1962. break;
  1963. case 2:
  1964. strTxt = "请求的操作无权限。";
  1965. break;
  1966. default:
  1967. strTxt = "操作失败,原因未知。";
  1968. break;
  1969. }
  1970. ans.attachment1 = strTxt.GetLength();
  1971. ans.attachment2 = strTxt;
  1972. ctx->Answer(Error_Succeed);
  1973. Dbg("Try to (option:%d) [%s] failed (%d): %s", req.mode, (LPCTSTR)strCurrent, nRes, (LPCTSTR)strTxt);
  1974. return nRes;
  1975. }
  1976. }
  1977. FileType type = FT_Unknown;
  1978. IsPathExisted(strCurrent, type);
  1979. int count = 0;
  1980. ans.count = 0;
  1981. ans.result = OPT_FILE_RES_INVALID;
  1982. bool bNeedToRefleshHeader = false;
  1983. bool bNeedToSetCtxEntities = false;
  1984. bool bNeedToRefleshEntity = false;
  1985. int updateLevel = 0;
  1986. switch(ctx->Req.mode)
  1987. {
  1988. case OPT_FILE_CMD_SPREAD: //0
  1989. {
  1990. DWORD dwRes = 0;
  1991. if(!bCurNull && (type == FT_Unknown || type == FT_File))
  1992. {
  1993. ans.result = OPT_FILE_RES_FAILED;
  1994. ans.attachment1 = GetErrorMessage(ans.attachment2, "请求的文件不存在或类型不正确。");
  1995. Dbg("Before Initial File Entity failed: %s", ans.attachment2.GetData());
  1996. break;
  1997. }
  1998. DWORD dwFilterAttributes = (DWORD)(ctx->Req.filter1);
  1999. if(bCurNull) {
  2000. #if defined(_MSC_VER)
  2001. dwRes = InitialVolumes();
  2002. #else
  2003. if (!InitialDirectoryEntity("/", dwRes, dwFilterAttributes)) {
  2004. ans.result = OPT_FILE_RES_FAILED;
  2005. ans.attachment1 = GetErrorMessage(ans.attachment2, "获取根目录列表失败");
  2006. Dbg("Initial File Entity failed: %s", ans.attachment2.GetData());
  2007. break;
  2008. }
  2009. #endif //_MSC_VER
  2010. }
  2011. else if(!InitialDirectoryEntity(strCurrent, dwRes, dwFilterAttributes))
  2012. {
  2013. ans.result = OPT_FILE_RES_FAILED;
  2014. ans.attachment1 = GetErrorMessage(ans.attachment2, "获取文件列表失败");
  2015. Dbg("Initial File Entity failed: %s", ans.attachment2.GetData());
  2016. break;
  2017. }
  2018. Dbg("%d VS %d", dwRes, m_FileEntry.SubFiles.GetCount());
  2019. LOG_ASSERT(dwRes == m_FileEntry.SubFiles.GetCount());
  2020. count = dwRes;
  2021. ans.result = OPT_FILE_RES_SUCCESS;
  2022. bNeedToSetCtxEntities = true;
  2023. bNeedToRefleshHeader = true;
  2024. }
  2025. break;
  2026. case OPT_FILE_CMD_EXECUTE://1
  2027. {
  2028. if(type != FT_File)
  2029. {
  2030. Dbg("Invalid file type !");
  2031. ans.result = OPT_FILE_RES_INVALID;
  2032. ans.attachment2 = "非可打开或执行的文件类型(目录或其他)";
  2033. ans.attachment1 = ans.attachment2.GetLength();
  2034. break;
  2035. }
  2036. LPCTSTR lpParam = NULL;
  2037. if(req.attachment1 > 0 && req.attachment2.GetLength() > 0)
  2038. lpParam = req.attachment2;
  2039. const DWORD dwRes = ExecuteFile(strCurrent, lpParam);
  2040. ans.result = dwRes ? OPT_FILE_RES_FAILED : OPT_FILE_RES_SUCCESS;
  2041. if (dwRes) {
  2042. #if defined(_MSC_VER)
  2043. ans.attachment1 = GetErrorMessage(ans.attachment2, "执行文件操作失败。");
  2044. Dbg("ExecuteFile failed: %s", (LPCTSTR)ans.attachment2);
  2045. #else
  2046. ans.attachment2 = "不支持该操作";
  2047. ans.attachment1 = ans.attachment2.GetLength();
  2048. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2049. #endif //_MSC_VER
  2050. }
  2051. }
  2052. break;
  2053. case OPT_FILE_CMD_DELETE: //2
  2054. case OPT_FILE_CMD_CLEAR: //3
  2055. {
  2056. bool bClear = !!(ctx->Req.mode == OPT_FILE_CMD_CLEAR);
  2057. if(!bClear) {Dbg("Delete flag.");}
  2058. if(type == FT_Unknown) {
  2059. ans.result = OPT_FILE_RES_INVALID;
  2060. ans.attachment2 = "所指定的文件不存在。";
  2061. ans.attachment1 = ans.attachment2.GetLength();
  2062. break;
  2063. }
  2064. #if defined(_MSC_VER)
  2065. if (type == FT_Volume) {
  2066. if (!bClear) {
  2067. ans.result = OPT_FILE_RES_INVALID;
  2068. ans.attachment2 = "该操作对卷类型的文件无效。";
  2069. ans.attachment1 = ans.attachment2.GetLength();
  2070. } else if (ClearDirRecursiveA(strCurrent)) {
  2071. ans.result = OPT_FILE_RES_SUCCESS;
  2072. bNeedToRefleshEntity = true;
  2073. } else {
  2074. ans.attachment2 = "清空卷操作执行失败。";
  2075. ans.attachment1 = ans.attachment2.GetLength();
  2076. ans.result = OPT_FILE_RES_FAILED;
  2077. }
  2078. break;
  2079. }
  2080. #endif //_MSC_VER
  2081. if((type == FT_Directory
  2082. && (
  2083. (!bClear && !RemoveDirRecursiveA(strCurrent))
  2084. || (bClear && !ClearDirRecursiveA(strCurrent))
  2085. ))
  2086. || (type == FT_File && !bClear && !RemoveFileA(strCurrent)))
  2087. {
  2088. ans.attachment1 = GetErrorMessage(ans.attachment2, ((!bClear) ? "删除操作执行失败。" : "清空操作执行失败。"));
  2089. Dbg("Delete(%d) or clear file failed: %s", !bClear, ans.attachment2.GetData());
  2090. ans.result = OPT_FILE_RES_FAILED;
  2091. break;
  2092. }
  2093. if(type == FT_File && bClear)
  2094. {//文件内容清理
  2095. //simple implement
  2096. FILE* stream;
  2097. SetLastError(0);
  2098. if((stream = fopen(strCurrent, "w+")) == NULL) {
  2099. ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
  2100. ans.result = OPT_FILE_RES_FAILED;
  2101. break;
  2102. }
  2103. if (fclose(stream)) {
  2104. Dbg("fclose(%s) failed", (LPCTSTR)strCurrent);
  2105. ans.attachment1 = GetErrorMessage(ans.attachment2, "清空文件内容执行失败。");
  2106. ans.result = OPT_FILE_RES_FAILED;
  2107. break;
  2108. }
  2109. }
  2110. ans.result = OPT_FILE_RES_SUCCESS;
  2111. bNeedToRefleshEntity = true;
  2112. if ((!bClear && type != FT_File) || (bClear && type == FT_File)) {
  2113. updateLevel = 1;
  2114. }
  2115. }
  2116. break;
  2117. case OPT_FILE_CMD_CREATE: //4
  2118. {
  2119. if ((type == FT_Directory && (req.attribute & 0x10)) || (type == FT_File && !(req.attribute & 0x10)) || type == FT_Volume) {
  2120. Dbg("Existed file occurs create(%d) ?", type);
  2121. ans.result = OPT_FILE_RES_FAILED;
  2122. ans.attachment2 = "目录或文件已存在。";
  2123. ans.attachment1 = ans.attachment2.GetLength();
  2124. break;
  2125. }
  2126. BOOL bRet = FALSE;
  2127. int depth = GetPathDepth(strCurrent);
  2128. if(depth <= 0)
  2129. {
  2130. Dbg("Invalid file path(%s)", (LPCTSTR)strCurrent);
  2131. ans.result = OPT_FILE_RES_FAILED;
  2132. ans.attachment2 = "非法文件路径或名称。";
  2133. ans.attachment1 = ans.attachment2.GetLength();
  2134. break;
  2135. }
  2136. if(req.attribute & 0x10) {
  2137. Dbg("Start to create directory");
  2138. if(!CreateDirA(strCurrent, TRUE))
  2139. {
  2140. ans.attachment1 = GetErrorMessage(ans.attachment2, "新建文件夹失败。");
  2141. Dbg("Create directory failed: %s", ans.attachment2.GetData());
  2142. ans.result = OPT_FILE_RES_FAILED;
  2143. break;
  2144. }
  2145. } else {
  2146. #if defined(RVC_OS_WIN)
  2147. if (depth == 1/*根目录下创建文件*/ || CreateParentDirA(strCurrent, TRUE)) {
  2148. DWORD dwNewAttr = FILE_ATTRIBUTE_NORMAL/* | req.attribute*/;
  2149. HANDLE hNewFile = CreateFileA(strCurrent, GENERIC_WRITE,
  2150. 0, NULL, CREATE_NEW, dwNewAttr, NULL);
  2151. if (hNewFile == INVALID_HANDLE_VALUE) {
  2152. ans.attachment1 = GetErrorMessage(ans.attachment2, "创建文件失败。");
  2153. Dbg("Create file failed: %s", ans.attachment2.GetData());
  2154. ans.result = OPT_FILE_RES_FAILED;
  2155. break;
  2156. }
  2157. if (req.content.GetLength() >= 0) {
  2158. DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
  2159. DWORD dwByteWritten = 0;
  2160. DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
  2161. LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2162. BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
  2163. dwBytesToWrite, &dwByteWritten, NULL);
  2164. UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2165. if (!bRes || dwByteWritten != dwBytesToWrite) {
  2166. ans.attachment1 = GetErrorMessage(ans.attachment2,
  2167. !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
  2168. Dbg("Write file failed: %s", ans.attachment2.GetData());
  2169. Dbg("Write file is incompletely(%u/%u)", dwByteWritten, dwBytesToWrite);
  2170. CloseHandle(hNewFile);
  2171. DeleteFileA(strCurrent);
  2172. ans.result = OPT_FILE_RES_FAILED;
  2173. break;
  2174. }
  2175. }
  2176. CloseHandle(hNewFile);
  2177. } else {
  2178. ans.attachment1 = GetErrorMessage(ans.attachment2, "创建目标文件所在目录失败。");
  2179. Dbg("Create parent directory failed: %s", (LPCTSTR)ans.attachment2);
  2180. ans.result = OPT_FILE_RES_FAILED;
  2181. break;
  2182. }
  2183. #else
  2184. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2185. ans.attachment2 = "不支持操作";
  2186. ans.attachment1 = ans.attachment2.GetLength();
  2187. break;
  2188. #endif //RVC_OS_WIN
  2189. }
  2190. ans.result = OPT_FILE_RES_SUCCESS;
  2191. bNeedToRefleshEntity = true;
  2192. updateLevel = 1;
  2193. }
  2194. break;
  2195. case OPT_FILE_CMD_APPEND: //5
  2196. #if defined(_MSC_VER)
  2197. {
  2198. if (type != FT_File) {
  2199. Dbg("file is not existed(%d) ?", type);
  2200. ans.result = OPT_FILE_RES_FAILED;
  2201. ans.attachment2 = "目标文件不存在或非文件类型。";
  2202. ans.attachment1 = ans.attachment2.GetLength();
  2203. break;
  2204. } else if (req.content.GetLength() <= 0) {
  2205. Dbg("invalid file content %d", req.content.GetLength());
  2206. ans.result = OPT_FILE_RES_FAILED;
  2207. ans.attachment2 = "写入的文件内容不存在。";
  2208. ans.attachment1 = ans.attachment2.GetLength();
  2209. break;
  2210. }
  2211. DWORD dwBytesToWrite = (DWORD)req.content.GetLength();
  2212. DWORD dwByteWritten = 0;
  2213. HANDLE hNewFile = CreateFileA(strCurrent, FILE_APPEND_DATA,
  2214. FILE_SHARE_READ, NULL, /*OPEN_EXISTING*/OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  2215. if (hNewFile == INVALID_HANDLE_VALUE) {
  2216. ans.attachment1 = GetErrorMessage(ans.attachment2, "打开文件失败。");
  2217. Dbg("open file failed: %s", (LPCTSTR)ans.attachment2);
  2218. ans.result = OPT_FILE_RES_FAILED;
  2219. break;
  2220. }
  2221. DWORD dwPos = SetFilePointer(hNewFile, 0, NULL, FILE_END);
  2222. LockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2223. BOOL bRes = WriteFile(hNewFile, req.content.GetData(),
  2224. dwBytesToWrite, &dwByteWritten, NULL);
  2225. UnlockFile(hNewFile, dwPos, 0, dwBytesToWrite, 0);
  2226. if (!bRes || dwByteWritten != dwBytesToWrite) {
  2227. ans.attachment1 = GetErrorMessage(ans.attachment2, !bRes ? "写入文件操作失败。" : "文件数据写入不完整。");
  2228. Dbg("Append file failed: %s", ans.attachment2.GetData());
  2229. Dbg("Append file is incompletely(%u/%u)", dwByteWritten, dwBytesToWrite);
  2230. ans.result = OPT_FILE_RES_FAILED;
  2231. CloseHandle(hNewFile);
  2232. DeleteFileA(strCurrent);
  2233. ans.result = OPT_FILE_RES_FAILED;
  2234. break;
  2235. }
  2236. CloseHandle(hNewFile);
  2237. ans.result = OPT_FILE_RES_SUCCESS;
  2238. bNeedToRefleshEntity = true;
  2239. updateLevel = 1;
  2240. }
  2241. #else
  2242. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2243. ans.attachment2 = "不支持操作";
  2244. ans.attachment1 = ans.attachment2.GetLength();
  2245. #endif //_MSC_VER
  2246. break;
  2247. case OPT_FILE_CMD_RENAME: //6
  2248. {
  2249. #if defined(_MSC_VER)
  2250. Dbg("Rename a file ? it would be critical...");
  2251. if (type == FT_Unknown || type == FT_Volume) {
  2252. Dbg("file is not existed(%d)?", type);
  2253. ans.result = OPT_FILE_RES_FAILED;
  2254. ans.attachment2 = type == FT_Unknown ? "目标文件不存在。" : "文件类型(卷)不支持当前操作。";
  2255. ans.attachment1 = ans.attachment2.GetLength();
  2256. break;
  2257. }
  2258. req.content = req.content.Trim();
  2259. if (req.content.GetLength() <= 0) {
  2260. Dbg("empty new file name ?");
  2261. ans.result = OPT_FILE_RES_FAILED;
  2262. ans.attachment2 = "传入新文件名参数为空。";
  2263. ans.attachment1 = ans.attachment2.GetLength();
  2264. break;
  2265. }
  2266. if (strchr(req.content, '\\') || strchr(req.content, '/')) {
  2267. Dbg("invalid new file name: %s", (LPCTSTR)req.content);
  2268. ans.result = OPT_FILE_RES_FAILED;
  2269. ans.attachment2 = "新文件名参数无效。";
  2270. ans.attachment1 = ans.attachment2.GetLength();
  2271. break;
  2272. }
  2273. const size_t st_len = nCurLen + req.content.GetLength();
  2274. char* path = new char[st_len];
  2275. ZeroMemory(path, st_len);
  2276. int res = 0;
  2277. if (path == NULL) {
  2278. res = 1;
  2279. LogWarn(Severity_Middle, Error_Resource, 0, "alloc path memory failed");
  2280. } else {
  2281. int dir_len = 0;
  2282. CSimpleStringA strNewName = req.content;
  2283. if ((dir_len = GetDirSplitPath(strCurrent, 1, path, st_len)) > 0) {
  2284. if (!req.attribute && type == FT_File) {
  2285. Dbg("save file-type suffix in rename mode.");
  2286. char tmp[MAX_PATH] = { 0 };
  2287. strcpy(tmp, strCurrent.GetData() + dir_len + 1);
  2288. char* pos = strrchr(tmp, '.');
  2289. if (pos) { strNewName += pos; }
  2290. }
  2291. strcat(path, SPLIT_SLASH_STR);
  2292. strcat(path, strNewName);
  2293. res = rename(strCurrent, path);
  2294. } else {
  2295. Dbg("GetDirSplitPath failed: %s vs %s", (LPCTSTR)strCurrent, path);
  2296. res = 1;
  2297. }
  2298. delete[] path;
  2299. path = NULL;
  2300. }
  2301. if (res) {
  2302. Dbg("rename failed: %d", errno);
  2303. ans.result = OPT_FILE_RES_FAILED;
  2304. ans.attachment2 = "重命名操作失败。";
  2305. ans.attachment1 = ans.attachment2.GetLength();
  2306. break;
  2307. }
  2308. ans.result = OPT_FILE_RES_SUCCESS;
  2309. bNeedToRefleshEntity = true;
  2310. updateLevel = 1;
  2311. #else
  2312. ans.result = OPT_FILE_RES_NOT_SUPPORT;
  2313. ans.attachment2 = "不支持操作";
  2314. ans.attachment1 = ans.attachment2.GetLength();
  2315. #endif //_MSC_VER
  2316. }
  2317. break;
  2318. default:
  2319. {
  2320. LogWarn(Severity_Low, Error_Unexpect, 0,
  2321. CSimpleStringA::Format("Unexpected file operation command : %d", ctx->Req.mode));
  2322. CSimpleStringA strTip = CSimpleStringA::Format("无法识别的操作指令(mode: %d)。", ctx->Req.mode);
  2323. ans.attachment1 = strTip.GetLength();
  2324. ans.attachment2 = strTip;
  2325. }
  2326. break;
  2327. }
  2328. if(ans.result == OPT_FILE_RES_SUCCESS)
  2329. {
  2330. if(bNeedToSetCtxEntities || bNeedToRefleshEntity)
  2331. {
  2332. bool bReInit = true;
  2333. if(bNeedToRefleshEntity)
  2334. {
  2335. DWORD dwCnt = 0;
  2336. CSimpleStringA strHeader = strCurrent;
  2337. if(updateLevel != 0)
  2338. {
  2339. char* pPath = new char[nCurLen+1];
  2340. if(pPath == NULL) bReInit = false;
  2341. else
  2342. {
  2343. UINT uRes = GetDirSplitPath(strHeader, updateLevel, pPath, nCurLen+1);
  2344. if(uRes == 0) bReInit = false;
  2345. strHeader = pPath;
  2346. delete[] pPath;
  2347. pPath = NULL;
  2348. }
  2349. }
  2350. if(bReInit)
  2351. {
  2352. bReInit = !!InitialDirectoryEntity(strHeader, dwCnt);
  2353. }
  2354. bNeedToRefleshHeader = true;
  2355. }
  2356. if(bReInit)
  2357. {
  2358. ConveyFileEntityToContext(ctx, bNeedToRefleshHeader);
  2359. }
  2360. }
  2361. }
  2362. else {
  2363. Dbg("attach1: %d", ans.attachment1);
  2364. Dbg("attach2: %s", ans.attachment2.GetData());
  2365. }
  2366. ctx->Answer(Error_Succeed);
  2367. return (ans.result);
  2368. }
  2369. DWORD ResourceWatcherFSM::ExecuteFile(LPCTSTR lpszFilePath, LPCTSTR lpParam)
  2370. {
  2371. DWORD dwRes = 0;
  2372. #if defined(_MSC_VER)
  2373. SHELLEXECUTEINFOA shell;
  2374. memset(&shell, 0, sizeof(SHELLEXECUTEINFOA));
  2375. shell.cbSize = sizeof(SHELLEXECUTEINFOA);
  2376. shell.lpFile = lpszFilePath;
  2377. shell.lpParameters = lpParam;
  2378. shell.fMask = SEE_MASK_INVOKEIDLIST;
  2379. shell.lpVerb = NULL;
  2380. shell.nShow = SW_SHOWDEFAULT;
  2381. if (!ShellExecuteExA(&shell)) {
  2382. dwRes = GetLastError();
  2383. int nRes = (int)shell.hInstApp;
  2384. Dbg("GLE=%u, InstApp=%d", dwRes, nRes);
  2385. switch (dwRes) {
  2386. case ERROR_NO_ACE_CONDITION:
  2387. LogWarn(Severity_Middle, Error_MethodNotFound, dwRes,
  2388. CSimpleStringA::Format("Target file(%s) association not available !", lpszFilePath));
  2389. break;
  2390. case ERROR_ACCESS_DENIED:
  2391. LogWarn(Severity_Middle, Error_NoPrivilege, dwRes,
  2392. CSimpleStringA::Format("Target file(%s) not privilege !", lpszFilePath));
  2393. break;
  2394. case ERROR_PATH_NOT_FOUND:
  2395. case ERROR_FILE_NOT_FOUND:
  2396. LogWarn(Severity_Middle, Error_NotExist, dwRes,
  2397. CSimpleStringA::Format("Target file(%s) not existed !", lpszFilePath));
  2398. break;
  2399. case ERROR_DLL_NOT_FOUND:
  2400. LogWarn(Severity_Middle, Error_NotExist, dwRes,
  2401. CSimpleStringA::Format("One of library file for Target(%s) not existed !", lpszFilePath));
  2402. break;
  2403. case ERROR_NOT_ENOUGH_MEMORY:
  2404. LogWarn(Severity_Middle, Error_Resource, dwRes,
  2405. CSimpleStringA::Format("Not enough memory for Target(%s) to perform !", lpszFilePath));
  2406. break;
  2407. case ERROR_SHARING_VIOLATION:
  2408. LogWarn(Severity_Middle, Error_Overflow, dwRes,
  2409. CSimpleStringA::Format("Violation occurred for Target(%s) to share !", lpszFilePath));
  2410. break;
  2411. default:
  2412. LogWarn(Severity_Middle, Error_Unexpect, dwRes,
  2413. CSimpleStringA::Format("Unpected condtion for Target(%s) to execute(%u) !"
  2414. , lpszFilePath, dwRes));
  2415. break;
  2416. }
  2417. }
  2418. #else
  2419. dwRes = 1;
  2420. #endif //_MSC_VER
  2421. return dwRes;
  2422. }
  2423. BOOL ResourceWatcherFSM::ConveyFileEntityToContext(const SpReqAnsContext<ResourceWatcherService_OperateFile_Req,
  2424. ResourceWatcherService_OperateFile_Ans>::Pointer& ctx
  2425. , BOOL bRefleshHeader /*= FALSE*/, DWORD dwFilterAttributes)
  2426. {
  2427. if(ctx == NULL) return FALSE;
  2428. #if defined(_MSC_VER)
  2429. ULARGE_INTEGER ilOffsetSize;
  2430. ilOffsetSize.QuadPart = 0;
  2431. const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
  2432. DWORD dwInheritForbidAttrs = 0UL;
  2433. if (bRefleshHeader) {
  2434. if (m_FileEntry.Current.mNameLength != 0) {
  2435. ilOffsetSize.LowPart = m_FileEntry.Current.mNameOffset;
  2436. ilOffsetSize.HighPart = m_FileEntry.Current.mNameLength;
  2437. GetSubFileName(m_FileEntry.FileNamesBuffer,
  2438. dwBufSize, ctx->Ans.header, &ilOffsetSize);
  2439. ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
  2440. ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
  2441. ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
  2442. ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
  2443. ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
  2444. if (!ctx->Ans.header.IsNullOrEmpty() && ctx->Ans.header.GetLength() > 0) {
  2445. if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
  2446. dwInheritForbidAttrs |= BS_DENY_DELETE;
  2447. Dbg("header-forbit:%s", ctx->Ans.header.GetData());
  2448. }
  2449. }
  2450. }
  2451. }
  2452. int count = m_FileEntry.SubFiles.GetCount();
  2453. int minusCount = 0;
  2454. for (int i = 0; i < count; ++i)
  2455. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
  2456. minusCount++;
  2457. count = count - minusCount;
  2458. ctx->Ans.count = count;
  2459. if (count > 0) {
  2460. if (count >= MAX_SUBFILES_COUNT) {
  2461. Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
  2462. std::vector<CSimpleFileShell> vtFileShells;
  2463. for (int i = 0; i < count; ++i) {
  2464. CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
  2465. vtFileShells.push_back(item);
  2466. }
  2467. sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
  2468. char szFormat[128] = { 0 };
  2469. count = MAX_SUBFILES_COUNT;
  2470. ctx->Ans.count = count;
  2471. ctx->Ans.fileAttributes.Init(count);
  2472. ctx->Ans.fileNames.Init(count);
  2473. ctx->Ans.ftCreates.Init(count);
  2474. ctx->Ans.ftModifieds.Init(count);
  2475. ctx->Ans.ftAccesses.Init(count);
  2476. ctx->Ans.fileSizes.Init(count);
  2477. ctx->Ans.forbidAttributes.Init(count);
  2478. ctx->Ans.reserved1.Init(count);
  2479. ctx->Ans.reserved2.Init(count);
  2480. for (int i = 0; i < count; ++i) {
  2481. CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
  2482. ilOffsetSize.LowPart = component->mNameOffset;
  2483. ilOffsetSize.HighPart = component->mNameLength;
  2484. if (component->mAttributes & dwFilterAttributes) {
  2485. CSimpleStringA strFileName;
  2486. GetSubFileName(m_FileEntry.FileNamesBuffer,
  2487. dwBufSize, strFileName, &ilOffsetSize);
  2488. Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
  2489. continue;
  2490. }
  2491. ctx->Ans.reserved1[i] = 0;
  2492. ctx->Ans.reserved2[i] = "";
  2493. ctx->Ans.fileAttributes[i] = component->mAttributes;
  2494. ctx->Ans.ftCreates[i] = component->mftCreate;
  2495. ctx->Ans.ftModifieds[i] = component->mftModified;
  2496. ctx->Ans.ftAccesses[i] = component->mftAccess;
  2497. ctx->Ans.fileSizes[i] = component->mFileSize;
  2498. //TODO: Need to judge whether need to calculate size of directory.
  2499. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2500. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2501. ctx->Ans.forbidAttributes[i] = 0;
  2502. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2503. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2504. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2505. CSimpleStringA csFilePath;
  2506. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2507. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2508. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2509. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2510. }
  2511. }
  2512. }
  2513. vtFileShells.clear();
  2514. } else {
  2515. ctx->Ans.fileAttributes.Init(count);
  2516. ctx->Ans.fileNames.Init(count);
  2517. ctx->Ans.ftCreates.Init(count);
  2518. ctx->Ans.ftModifieds.Init(count);
  2519. ctx->Ans.ftAccesses.Init(count);
  2520. ctx->Ans.fileSizes.Init(count);
  2521. ctx->Ans.forbidAttributes.Init(count);
  2522. ctx->Ans.reserved1.Init(count);
  2523. ctx->Ans.reserved2.Init(count);
  2524. for (int i = 0; i < count; ++i) {
  2525. ilOffsetSize.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
  2526. ilOffsetSize.HighPart = m_FileEntry.SubFiles[i].mNameLength;
  2527. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
  2528. CSimpleStringA strFileName;
  2529. GetSubFileName(m_FileEntry.FileNamesBuffer,
  2530. dwBufSize, strFileName, &ilOffsetSize);
  2531. Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
  2532. continue;
  2533. }
  2534. ctx->Ans.reserved1[i] = 0;
  2535. ctx->Ans.reserved2[i] = "";
  2536. ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
  2537. ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
  2538. ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
  2539. ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
  2540. ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
  2541. //TODO: Need to judge whether need to calculate size of directory.
  2542. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2543. ctx->Ans.forbidAttributes[i] = 0;
  2544. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2545. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2546. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2547. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2548. CSimpleStringA csFilePath;
  2549. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2550. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2551. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2552. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2553. }
  2554. }
  2555. }
  2556. }
  2557. }
  2558. #else
  2559. ULARGE_INTEGER ilOffsetSize;
  2560. ilOffsetSize.QuadPart = 0;
  2561. const DWORD dwBufSize = m_FileEntry.FileNamesBuffer.GetCount();
  2562. DWORD dwInheritForbidAttrs = 0UL;
  2563. if (bRefleshHeader) {
  2564. if (m_FileEntry.Current.mNameLength != 0) {
  2565. ilOffsetSize.u.LowPart = m_FileEntry.Current.mNameOffset;
  2566. ilOffsetSize.u.HighPart = m_FileEntry.Current.mNameLength;
  2567. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.header, &ilOffsetSize);
  2568. ctx->Ans.fileAttribute = m_FileEntry.Current.mAttributes;
  2569. ctx->Ans.ftAccess = m_FileEntry.Current.mftAccess;
  2570. ctx->Ans.ftModified = m_FileEntry.Current.mftModified;
  2571. ctx->Ans.ftCreate = m_FileEntry.Current.mftCreate;
  2572. ctx->Ans.fileSize = m_FileEntry.Current.mFileSize;
  2573. if (!ctx->Ans.header.IsNullOrEmpty()) {
  2574. if (InBlackListOrNot(ctx->Ans.header, OPT_FILE_CMD_DELETE)) {
  2575. dwInheritForbidAttrs |= BS_DENY_DELETE;
  2576. Dbg("header-forbit:%s", ctx->Ans.header.GetData());
  2577. }
  2578. }
  2579. }
  2580. }
  2581. int count = m_FileEntry.SubFiles.GetCount();
  2582. int minusCount = 0;
  2583. for (int i = 0; i < count; ++i)
  2584. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes)
  2585. minusCount++;
  2586. count = count - minusCount;
  2587. ctx->Ans.count = count;
  2588. if (count > 0) {
  2589. if (count >= MAX_SUBFILES_COUNT) {
  2590. Dbg("Exceedingly max file count: %d >= %d", count, MAX_SUBFILES_COUNT);
  2591. std::vector<CSimpleFileShell> vtFileShells;
  2592. for (int i = 0; i < count; ++i) {
  2593. CSimpleFileShell item = RetriveSubFile(&m_FileEntry, i);
  2594. vtFileShells.push_back(item);
  2595. }
  2596. sort(vtFileShells.begin(), vtFileShells.end(), _CompareFunc);
  2597. char szFormat[128] = { 0 };
  2598. count = MAX_SUBFILES_COUNT;
  2599. ctx->Ans.count = count;
  2600. ctx->Ans.reserved1.Init(count);
  2601. ctx->Ans.reserved2.Init(count);
  2602. ctx->Ans.fileAttributes.Init(count);
  2603. ctx->Ans.fileNames.Init(count);
  2604. ctx->Ans.ftCreates.Init(count);
  2605. ctx->Ans.ftModifieds.Init(count);
  2606. ctx->Ans.ftAccesses.Init(count);
  2607. ctx->Ans.fileSizes.Init(count);
  2608. ctx->Ans.forbidAttributes.Init(count);
  2609. for (int i = 0; i < count; ++i) {
  2610. CSimpleFileComponent* component = (CSimpleFileComponent*)vtFileShells[i];
  2611. ilOffsetSize.u.LowPart = component->mNameOffset;
  2612. ilOffsetSize.u.HighPart = component->mNameLength;
  2613. if (component->mAttributes & dwFilterAttributes) {
  2614. CSimpleStringA strFileName;
  2615. GetSubFileName(m_FileEntry.FileNamesBuffer,dwBufSize, strFileName, &ilOffsetSize);
  2616. Dbg("%s reserved: 0x%X", strFileName.GetData(), component->mAttributes);
  2617. continue;
  2618. }
  2619. ctx->Ans.reserved1[i] = 0;
  2620. ctx->Ans.reserved2[i] = "";
  2621. ctx->Ans.fileAttributes[i] = component->mAttributes;
  2622. ctx->Ans.ftCreates[i] = component->mftCreate;
  2623. ctx->Ans.ftModifieds[i] = component->mftModified;
  2624. ctx->Ans.ftAccesses[i] = component->mftAccess;
  2625. ctx->Ans.fileSizes[i] = component->mFileSize;
  2626. //TODO: Need to judge whether need to calculate size of directory.
  2627. GetSubFileName(m_FileEntry.FileNamesBuffer, dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2628. ctx->Ans.forbidAttributes[i] = 0;
  2629. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2630. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2631. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2632. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2633. CSimpleStringA csFilePath;
  2634. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2635. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2636. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2637. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2638. }
  2639. }
  2640. }
  2641. vtFileShells.clear();
  2642. } else {
  2643. ctx->Ans.fileAttributes.Init(count);
  2644. ctx->Ans.fileNames.Init(count);
  2645. ctx->Ans.ftCreates.Init(count);
  2646. ctx->Ans.ftModifieds.Init(count);
  2647. ctx->Ans.ftAccesses.Init(count);
  2648. ctx->Ans.fileSizes.Init(count);
  2649. ctx->Ans.forbidAttributes.Init(count);
  2650. ctx->Ans.reserved1.Init(count);
  2651. ctx->Ans.reserved2.Init(count);
  2652. for (int i = 0; i < count; ++i) {
  2653. ilOffsetSize.u.LowPart = m_FileEntry.SubFiles[i].mNameOffset;
  2654. ilOffsetSize.u.HighPart = m_FileEntry.SubFiles[i].mNameLength;
  2655. if (m_FileEntry.SubFiles[i].mAttributes & dwFilterAttributes) {
  2656. CSimpleStringA strFileName;
  2657. GetSubFileName(m_FileEntry.FileNamesBuffer,dwBufSize, strFileName, &ilOffsetSize);
  2658. Dbg("%s reserved: 0x%X", strFileName.GetData(), m_FileEntry.SubFiles[i].mAttributes);
  2659. continue;
  2660. }
  2661. ctx->Ans.reserved1[i] = 0;
  2662. ctx->Ans.reserved2[i] = "";
  2663. ctx->Ans.fileAttributes[i] = m_FileEntry.SubFiles[i].mAttributes;
  2664. ctx->Ans.ftCreates[i] = m_FileEntry.SubFiles[i].mftCreate;
  2665. ctx->Ans.ftModifieds[i] = m_FileEntry.SubFiles[i].mftModified;
  2666. ctx->Ans.ftAccesses[i] = m_FileEntry.SubFiles[i].mftAccess;
  2667. ctx->Ans.fileSizes[i] = m_FileEntry.SubFiles[i].mFileSize;
  2668. //TODO: Need to judge whether need to calculate size of directory.
  2669. GetSubFileName(m_FileEntry.FileNamesBuffer,dwBufSize, ctx->Ans.fileNames[i], &ilOffsetSize);
  2670. ctx->Ans.forbidAttributes[i] = 0;
  2671. Dbg("ADD %d: %s", __LINE__, ctx->Ans.fileNames[i].GetData());
  2672. if (m_FileEntry.Current.mNameLength == 0 && ctx->Ans.fileAttributes[i] == 0) {
  2673. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2674. } else if (!ctx->Ans.fileNames[i].IsNullOrEmpty()) {
  2675. CSimpleStringA csFilePath;
  2676. GetFullFilePath(&m_FileEntry, i, csFilePath);
  2677. if (InBlackListOrNot(csFilePath, OPT_FILE_CMD_DELETE)) {
  2678. ctx->Ans.forbidAttributes[i] |= BS_DENY_DELETE;
  2679. Dbg("fobbitten FullPath: %s", (LPCTSTR)csFilePath);
  2680. }
  2681. }
  2682. }
  2683. }
  2684. }
  2685. #endif //_MSC_VER
  2686. //Free action for saving memory.
  2687. m_FileEntry.SubFiles.Clear();
  2688. m_FileEntry.FileNamesBuffer.Clear();
  2689. m_FileEntry.Current.Clear();
  2690. return TRUE;
  2691. }
  2692. int ResourceWatcherFSM::FilterFilePathAhead(LPCTSTR lpszPath, const int option)
  2693. {
  2694. #if defined(RVC_OS_WIN)
  2695. size_t len = strlen(lpszPath);
  2696. if (!((lpszPath[0] <= 'z' && lpszPath[0] >= 'a') || (lpszPath[0] <= 'Z' && lpszPath[0] >= 'A'))
  2697. || lpszPath[1] != ':') {
  2698. Dbg("illegal disk format path !");
  2699. return -2;
  2700. }
  2701. const char disk = lpszPath[0];
  2702. if (disk >= 'a' && disk <= 'z') disk -= 32;
  2703. if (!sBDiskValStatus[int(disk - 'A')]) {
  2704. Dbg("Specified disk(%c) not existed", disk);
  2705. return -3;
  2706. }
  2707. char* path = new char[len + 1];
  2708. LOG_ASSERT(path != NULL);
  2709. memset(path, 0, sizeof(char) * (len + 1));
  2710. memcpy(path, lpszPath, len);
  2711. path[len] = '\0';
  2712. int pos = len - 1;
  2713. for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos) {
  2714. ;//
  2715. }
  2716. path[pos + 1] = '\0';
  2717. len = strlen(path);
  2718. if (len <= 1) {
  2719. delete[] path;
  2720. return -1;
  2721. }
  2722. else if (len == 2 && option == OPT_FILE_CMD_DELETE) {
  2723. /*disk volumn to delete*/
  2724. delete[] path;
  2725. return 1;
  2726. }
  2727. if (InBlackListOrNot(path, option)) {
  2728. delete[] path;
  2729. return 2;
  2730. }
  2731. delete[] path;
  2732. return 0;
  2733. #else
  2734. size_t len = strlen(lpszPath);
  2735. if (lpszPath[0] != '/') {
  2736. Dbg("illegal disk format path !");
  2737. return -2;
  2738. }
  2739. char* path = new char[len + 1];
  2740. LOG_ASSERT(path != NULL);
  2741. memset(path, 0, sizeof(char) * (len + 1));
  2742. memcpy(path, lpszPath, len);
  2743. path[len] = '\0';
  2744. int pos = len - 1;
  2745. for (; pos >= 0 && (path[pos] == '\\' || path[pos] == '/'); --pos) {
  2746. ;//
  2747. }
  2748. path[pos + 1] = '\0';
  2749. len = strlen(path);
  2750. if (len < 1) {
  2751. delete[] path;
  2752. return -1;
  2753. } else if (len == 1 && option == OPT_FILE_CMD_DELETE) {
  2754. /*disk volumn to delete*/
  2755. delete[] path;
  2756. return 1;
  2757. }
  2758. if (InBlackListOrNot(path, option)) {
  2759. delete[] path;
  2760. return 2;
  2761. }
  2762. delete[] path;
  2763. return 0;
  2764. #endif //RVC_OS_WIN
  2765. }
  2766. BOOL ResourceWatcherFSM::InBlackListOrNot(LPCTSTR lpszPath, const int option)
  2767. {
  2768. BOOL bForbidden = FALSE;
  2769. LOG_ASSERT(lpszPath != NULL && strlen(lpszPath) != 0);
  2770. DWORD dwRequredAttr = 0;
  2771. switch(option)
  2772. {
  2773. case OPT_FILE_CMD_SPREAD:
  2774. dwRequredAttr |= BS_DENY_READ;
  2775. break;
  2776. case OPT_FILE_CMD_EXECUTE:
  2777. dwRequredAttr |= BS_DENY_EXECUTE;
  2778. break;
  2779. case OPT_FILE_CMD_CREATE:
  2780. dwRequredAttr |= BS_DENY_CREATE;
  2781. break;
  2782. case OPT_FILE_CMD_DELETE:
  2783. case OPT_FILE_CMD_CLEAR:
  2784. case OPT_FILE_CMD_RENAME:
  2785. dwRequredAttr |= BS_DENY_DELETE;
  2786. break;
  2787. case OPT_FILE_CMD_APPEND:
  2788. dwRequredAttr |= BS_DENY_MODIFY;
  2789. break;
  2790. default:
  2791. Dbg("Unexpcted option: %d, allow it determined by later process.", option);
  2792. return bForbidden;
  2793. break;
  2794. }
  2795. const size_t len = strlen(lpszPath);
  2796. char* temp_path = new char[len+1];
  2797. if(temp_path == NULL) {
  2798. Dbg("new temp_path failed");
  2799. return bForbidden;
  2800. }
  2801. memset(temp_path, 0, sizeof(char)*(len+1));
  2802. strcpy_s(temp_path, len+1, lpszPath);
  2803. for (size_t i = 0; i < len; ++i) {
  2804. #if defined(_MSC_VER)
  2805. if (temp_path[i] == '/')
  2806. temp_path[i] = '\\';
  2807. #else
  2808. if (temp_path[i] == '\\')
  2809. temp_path[i] = '/';
  2810. #endif //_MSC_VER
  2811. }
  2812. lpszPath = temp_path;
  2813. for(const_bs_iter cit = m_forbidDirList.cbegin(); cit != m_forbidDirList.cend() && !bForbidden; ++cit)
  2814. {
  2815. const bs_key& path = cit->first;
  2816. const bs_value& resist = cit->second;
  2817. const size_t n = strlen(path.c_str());
  2818. if(dwRequredAttr & resist)
  2819. {
  2820. if(path[0] == '*') {
  2821. bForbidden = TRUE;
  2822. Dbg("Forbit0");
  2823. break;
  2824. }
  2825. if(!_strnicmp(lpszPath, path.c_str(), min(len, n)))
  2826. {
  2827. if(len > n && (lpszPath[n] == '\\' || lpszPath[n] == '/') && (resist & BS_DENY_INHERITED))
  2828. { bForbidden = TRUE; Dbg("forbit1"); }
  2829. if(len == n)
  2830. { bForbidden = TRUE; Dbg("forbit2"); }
  2831. if(len < n)
  2832. {
  2833. FileType ft;
  2834. if(IsPathExisted(path.c_str(), ft)) {
  2835. bForbidden = TRUE;
  2836. Dbg("forbit3");
  2837. }
  2838. }
  2839. }
  2840. }
  2841. }
  2842. if(temp_path) {
  2843. delete[] temp_path;
  2844. temp_path = NULL;
  2845. }
  2846. return bForbidden;
  2847. }
  2848. void ResourceWatcherFSM::InitBlackList()
  2849. {
  2850. LOG_FUNCTION();
  2851. m_forbidDirList.clear();
  2852. DWORD dwDenyAttr;
  2853. #if defined(_MSC_VER)
  2854. const int INFO_BUFFER_SIZE = MAX_PATH;
  2855. char infoBuf[INFO_BUFFER_SIZE];
  2856. DWORD bufCharCount = INFO_BUFFER_SIZE;
  2857. char sys_disk = '\0';
  2858. bufCharCount = INFO_BUFFER_SIZE;
  2859. if (!GetComputerName(infoBuf, &bufCharCount))
  2860. Dbg("GetComputerName failed, GLE=%u", GetLastError());
  2861. else
  2862. Dbg("Computer name: %s", infoBuf);
  2863. // Get and display the user name.
  2864. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2865. bufCharCount = INFO_BUFFER_SIZE;
  2866. if (!GetUserName(infoBuf, &bufCharCount))
  2867. Dbg("GetUserName failed, GLE=%u", GetLastError());
  2868. else
  2869. Dbg("User name: %s", infoBuf);
  2870. // All file cannot be executed !! -Josephus@2017612 9:29:01
  2871. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2872. infoBuf[0] = '*', infoBuf[1] = '\0';
  2873. dwDenyAttr = BS_DENY_EXECUTE | BS_DENY_INHERITED;
  2874. Dbg("Add All file filter: %s - 0x%X", infoBuf, dwDenyAttr);
  2875. m_forbidDirList.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  2876. // Get and display the system directory.
  2877. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2878. if (!GetSystemDirectory(infoBuf, INFO_BUFFER_SIZE)) {
  2879. Dbg("GetSystemDirectory failed, GLE=%u", GetLastError());
  2880. } else {
  2881. dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  2882. Dbg("Add System Directory: %s - 0x%X", infoBuf, dwDenyAttr);
  2883. m_forbidDirList.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  2884. sys_disk = infoBuf[0];
  2885. if (sys_disk >= 'a' && sys_disk <= 'z') sys_disk -= 32;
  2886. int diskNo = sys_disk - 'A';
  2887. LOG_ASSERT(sBDiskValStatus[diskNo]);
  2888. sBDiskValStatus[diskNo] = sBDiskValStatus[diskNo] + 2; //Set system disk flag
  2889. }
  2890. // Get and display the Windows directory.
  2891. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2892. if (!GetWindowsDirectory(infoBuf, INFO_BUFFER_SIZE)) {
  2893. Dbg("GetWindowsDirectory failed, GLE=%u", GetLastError());
  2894. } else {
  2895. dwDenyAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  2896. Dbg("Add Windows Directory: %s - 0x%X", infoBuf, dwDenyAttr);
  2897. m_forbidDirList.insert(BlackSheetPair(string(infoBuf), dwDenyAttr));
  2898. }
  2899. if (sys_disk != '\0') {
  2900. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  2901. //////////////////////////////////////////////////////////////////////////
  2902. LOG_ASSERT(INFO_BUFFER_SIZE > 4);
  2903. infoBuf[0] = sys_disk;
  2904. infoBuf[1] = ':';
  2905. infoBuf[2] = '\\';
  2906. infoBuf[3] = '\0';
  2907. Dbg("Start to Add system limited path: %d", LIMITED_SYS_COUNT);
  2908. const DWORD dwSysAttr = BS_DENY_DELETE/* | BS_DENY_EXECUTE*/ | BS_DENY_INHERITED;
  2909. for (int i = 0; i < LIMITED_SYS_COUNT; ++i) {
  2910. string strfullPath = infoBuf;
  2911. strfullPath += LIMITED_SYS_PATH(i);
  2912. if (m_forbidDirList.find(strfullPath) == m_forbidDirList.end()) {
  2913. Dbg("Add %s - 0x%X", strfullPath.c_str(), dwSysAttr);
  2914. m_forbidDirList[strfullPath] = dwSysAttr;
  2915. }
  2916. }
  2917. }
  2918. #endif //_MSC_VER
  2919. //////////////////////////////////////////////////////////////////////////
  2920. CSimpleStringA strPath;
  2921. if(GetEntityBase()->GetFunction()->GetPath("UploadVideo", strPath) == Error_Succeed)
  2922. {
  2923. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  2924. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  2925. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  2926. }
  2927. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2928. if(GetEntityBase()->GetFunction()->GetPath("UploadPhoto", strPath) == Error_Succeed)
  2929. {
  2930. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  2931. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  2932. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  2933. }
  2934. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2935. if(GetEntityBase()->GetFunction()->GetPath("Cfg", strPath) == Error_Succeed)
  2936. {
  2937. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  2938. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  2939. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  2940. }
  2941. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2942. if(GetEntityBase()->GetFunction()->GetPath("Dep", strPath) == Error_Succeed)
  2943. {
  2944. dwDenyAttr = BS_DENY_DELETE | BS_DENY_CREATE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  2945. Dbg("Add %s - 0x%X", (LPCTSTR)strPath, dwDenyAttr);
  2946. m_forbidDirList[string(strPath.GetData())] = dwDenyAttr;
  2947. }
  2948. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2949. if(GetEntityBase()->GetFunction()->GetPath("Base", strPath) == Error_Succeed)
  2950. {
  2951. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2952. dwDenyAttr = BS_DENY_DELETE | BS_DENY_EXECUTE | BS_DENY_INHERITED;
  2953. const size_t len = strPath.GetLength();
  2954. char* path = new char[len+1];
  2955. //Run Directory
  2956. if(path && (ZeroMemory(path, len+1), GetDirSplitPath(strPath, 2, path, len+1) > 0))
  2957. {
  2958. //Dbg("Add %s - 0x%X", path, dwDenyAttr);
  2959. //m_forbidDirList[string(path)] = dwDenyAttr;
  2960. }
  2961. if(path)
  2962. {
  2963. strPath = path;
  2964. delete[] path;
  2965. }
  2966. CSimpleStringA strPathInner;
  2967. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2968. strPathInner = strPath + SPLIT_SLASH_STR + "hardwarecfg";
  2969. dwDenyAttr = BS_DENY_DELETE | BS_DENY_MODIFY | BS_DENY_INHERITED;
  2970. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  2971. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  2972. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2973. strPathInner = strPath + SPLIT_SLASH_STR + "runinfo" + SPLIT_SLASH_STR + "kmc";
  2974. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  2975. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  2976. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  2977. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2978. strPathInner = strPath + SPLIT_SLASH_STR + "version";
  2979. dwDenyAttr = BS_DENY_DELETE | BS_DENY_INHERITED;
  2980. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  2981. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  2982. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2983. dwDenyAttr = BS_DENY_MODIFY;
  2984. strPathInner = strPath + SPLIT_SLASH_STR + "version" + SPLIT_SLASH_STR + "active.txt";
  2985. Dbg("Add %s - 0x%X", (LPCTSTR)strPathInner, dwDenyAttr);
  2986. m_forbidDirList[string(strPathInner.GetData())] = dwDenyAttr;
  2987. }
  2988. Dbg("ran at: %s::%d", __FUNCTION__, __LINE__);
  2989. }
  2990. #if defined(RVC_OS_WIN)
  2991. BOOL ResourceWatcherFSM::RetrieveSpecificedEventLogs(const LPEVENTLOGPARAM pEvtLogFilter,
  2992. LPCTSTR lpszEvtFileName, DWORD& dwEntries)
  2993. {
  2994. LOG_FUNCTION();
  2995. CEventLog* pEvtLog = NULL;
  2996. if (pEvtLogFilter->fApplication) {
  2997. pEvtLog = new CEventLog(APPLICATION_LOG);
  2998. } else if (pEvtLogFilter->fSystem) {
  2999. pEvtLog = new CEventLog(SYSTEM_LOG);
  3000. } else if (pEvtLogFilter->fSecurity) {
  3001. pEvtLog = new CEventLog(SECURITY_LOG);
  3002. #ifdef WIDE_CONDITION
  3003. } else if (pEvtLogFilter->fCustom && wcslen(pEvtLogFilter->lpszCustomEventName) > 0) {
  3004. #else
  3005. } else if (pEvtLogFilter->fCustom && strlen(pEvtLogFilter->lpszCustomEventName) > 0) {
  3006. #endif
  3007. pEvtLog = new CEventLog(pEvtLogFilter->lpszCustomEventName, TRUE);
  3008. }
  3009. if (pEvtLog == NULL || !pEvtLog->IsInitialized()) {
  3010. if (pEvtLog)
  3011. delete pEvtLog;
  3012. return FALSE;
  3013. }
  3014. #ifdef WIDE_CONDITION
  3015. CSimpleStringW strwFileName = CSimpleStringA2W(CSimpleStringA(lpszEvtFileName));
  3016. pEvtLog->InitializeLogFile(std::wstring(strwFileName));
  3017. #else
  3018. pEvtLog->InitializeLogFile(std::string(lpszEvtFileName));
  3019. #endif
  3020. dwEntries = pEvtLog->FilterEventLog(pEvtLogFilter->lpszSourceEventName
  3021. , pEvtLogFilter->wEventType
  3022. , pEvtLogFilter->dwEventId
  3023. , pEvtLogFilter->dwTimeBegin
  3024. , pEvtLogFilter->dwTimeEnd);
  3025. if (pEvtLog)
  3026. delete pEvtLog;
  3027. return TRUE;
  3028. }
  3029. DWORD ResourceWatcherFSM::GetEventLog(SpReqAnsContext<ResourceWatcherService_ExtractEventLog_Req,
  3030. ResourceWatcherService_ExtractEventLog_Ans>::Pointer ctx)
  3031. {
  3032. LOG_FUNCTION();
  3033. DWORD dwEntries = 0;
  3034. CHAR szEvtFile[MAX_PATH] = { 0 };
  3035. memset(szEvtFile, 0, sizeof(CHAR) * MAX_PATH);
  3036. if (!CombineTheEvtxFileName(m_strTerminalNo, szEvtFile)) {
  3037. ctx->Ans.entries = 0;
  3038. ctx->Ans.information = "初始化事件日志文件名失败";
  3039. ctx->Answer(Error_Succeed);
  3040. if (ExistsFileA(szEvtFile)) {
  3041. Dbg("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
  3042. }
  3043. return 0;
  3044. }
  3045. EVENTLOGPARAM filterParam = { 0 };
  3046. filterParam.wEventType = ctx->Req.evtLevel == 0x00FF ? 0 : ctx->Req.evtLevel;
  3047. BOOL bResult = TRUE;
  3048. DWORD dwResult = ERROR_SUCCESS;
  3049. Dbg("duration: 0x04X", ctx->Req.duration);
  3050. if (ctx->Req.duration == DURAITON_CUSTOM) {
  3051. ULONGLONG ullStart = ctx->Req.startTime;
  3052. ULONGLONG ullEnd = ctx->Req.endTime;
  3053. dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
  3054. &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), &ullStart, &ullEnd);
  3055. } else {
  3056. dwResult = CalSpecifiedSecondsFrom1970(ctx->Req.duration,
  3057. &(filterParam.dwTimeBegin), &(filterParam.dwTimeEnd), NULL, NULL);
  3058. }
  3059. if (dwResult != ERROR_SUCCESS) {
  3060. ctx->Ans.entries = 0;
  3061. ctx->Ans.information = "时间筛选参数错误";
  3062. ctx->Answer(Error_Succeed);
  3063. return 0;
  3064. }
  3065. if (!ctx->Req.evtSrcEventName.IsNullOrEmpty()) {
  3066. #ifdef WIDE_CONDITION
  3067. CSimpleStringW wSrvEventName = CSimpleStringA2W(ctx->Req.evtSrcEventName);
  3068. wcscpy_s(filterParam.lpszSourceEventName, wSrvEventName);
  3069. #else
  3070. strcpy_s(filterParam.lpszSourceEventName, ctx->Req.evtSrcEventName);
  3071. #endif
  3072. }
  3073. WORD wEventTypeMask = ctx->Req.evtName == 0 ? 0x00FF : ctx->Req.evtName;
  3074. Dbg("wEventTypeMask : 0x%04X", wEventTypeMask);
  3075. if ((wEventTypeMask & 0x0001) == 0x0001) {
  3076. DWORD dwRes = 0;
  3077. filterParam.fApplication = TRUE;
  3078. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3079. Dbg("[%s]Retrieve application event log returned: %u",
  3080. bResult ? "Success" : "Failed", dwRes);
  3081. if (bResult) {
  3082. dwEntries += dwRes;
  3083. }
  3084. filterParam.fApplication = FALSE;
  3085. }
  3086. if ((wEventTypeMask & 0x0002) == 0x0002) {
  3087. DWORD dwRes = 0;
  3088. filterParam.fSecurity = TRUE;
  3089. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3090. Dbg("[%s]Retrieve security event log returned: %u",
  3091. bResult ? "Success" : "Failed", dwRes);
  3092. if (bResult) {
  3093. dwEntries += dwRes;
  3094. }
  3095. filterParam.fSecurity = FALSE;
  3096. }
  3097. if ((wEventTypeMask & 0x0008) == 0x0008) {
  3098. DWORD dwRes = 0;
  3099. filterParam.fSystem = TRUE;
  3100. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3101. Dbg("[%s]Retrieve system event log returned: %u",
  3102. bResult ? "Success" : "Failed", dwRes);
  3103. if (bResult) {
  3104. dwEntries += dwRes;
  3105. }
  3106. filterParam.fSystem = FALSE;
  3107. }
  3108. if ((wEventTypeMask & 0x0100) == 0x0100) {
  3109. DWORD dwRes = 0;
  3110. filterParam.fCustom = TRUE;
  3111. if (!ctx->Req.cusEvtFileName.IsNullOrEmpty()) {
  3112. #ifdef WIDE_CONDITION
  3113. CSimpleStringW strwFileName = CSimpleStringA2W(ctx->Req.cusEvtFileName);
  3114. wcscpy_s(filterParam.lpszCustomEventName, strwFileName);
  3115. Dbg("Custom event log path: %s", ctx->Req.cusEvtFileName);
  3116. #else
  3117. strcpy_s(filterParam.lpszCustomEventName, ctx->Req.cusEvtFileName);
  3118. Dbg("Custom event log path: %s", filterParam.lpszCustomEventName);
  3119. #endif
  3120. }
  3121. bResult = RetrieveSpecificedEventLogs(&filterParam, szEvtFile, dwRes);
  3122. Dbg("[%s]Retrieve custom event log returned: %u",
  3123. bResult ? "Success" : "Failed", dwRes);
  3124. if (bResult) {
  3125. dwEntries += dwRes;
  3126. }
  3127. filterParam.fCustom = FALSE;
  3128. }
  3129. if (dwEntries == 0) {
  3130. ctx->Ans.entries = 0;
  3131. LogWarn(Severity_Middle, Error_Unexpect, 0, "The Count of event log is Zero!");
  3132. ctx->Ans.information = "未找到相关的系统事件日志";
  3133. if (ExistsFileA(szEvtFile)) {
  3134. Dbg("Remove file(%s) returned: %d", szEvtFile, RemoveFileA(szEvtFile));
  3135. }
  3136. } else {
  3137. ctx->Ans.entries = dwEntries;
  3138. ctx->Ans.evtLogFileName = szEvtFile;
  3139. Dbg("Total count of event log: %u", dwEntries);
  3140. }
  3141. ctx->Answer(Error_Succeed);
  3142. return dwEntries;
  3143. }
  3144. DWORD ResourceWatcherFSM::CombineTheEvtxFileName(LPCTSTR lpszTerminalNo, CHAR szEvtxFileName[])
  3145. {
  3146. CSimpleStringA strPath;
  3147. if(lpszTerminalNo == NULL || strlen(lpszTerminalNo) == 0)
  3148. {
  3149. LogError(Severity_Middle, Error_Param, 0, "TerminalNo is nullptr");
  3150. return 0;
  3151. }
  3152. if(GetEntityBase()->GetFunction()->GetPath("Temp", strPath) != Error_Succeed
  3153. || strPath.IsNullOrEmpty())
  3154. {
  3155. LogError(Severity_Middle, Error_Unexpect, 0, "GetPath about Temp failed");
  3156. return 0;
  3157. }
  3158. if(!ExistsDirA(strPath)) {
  3159. if(!CreateDirRecursiveA(strPath)) {
  3160. LogError(Severity_Middle, Error_Unexpect, 0, "CreateDirRecursiveA failed");
  3161. return 0;
  3162. }
  3163. }
  3164. SYSTEMTIME st, stLocal;
  3165. GetSystemTime(&st);
  3166. SystemTimeToTzSpecificLocalTime(NULL, &st, &stLocal);
  3167. #ifdef WIDE_CONDITION
  3168. WCHAR fileName[MAX_PATH] = { 0 };
  3169. CSimpleStringW strwPath = CSimpleStringA2W(strPath);
  3170. CSimpleStringW lpwszTerminalNo = CSimpleStringA2W(CSimpleStringA(lpszTerminalNo));
  3171. swprintf_s(fileName, L"%ws\\%ws-%d%02d%02d-%02d_%02d_%02d", (LPCWSTR)strwPath, (LPCWSTR)lpwszTerminalNo,
  3172. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  3173. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3174. wcscat_s(fileName, EXT_EVTLOG_NAME);
  3175. CSimpleStringA lpszFileName = CSimpleStringW2A(CSimpleStringW(fileName));
  3176. strcpy_s(szEvtxFileName, MAX_PATH, lpszFileName);
  3177. Dbg("Combined EventLog FilePah: %s", szEvtxFileName);
  3178. return strlen(szEvtxFileName);
  3179. #else
  3180. CHAR fileName[MAX_PATH] = { 0 };
  3181. sprintf_s(fileName, "%s\\%s-%d%02d%02d-%02d_%02d_%02d", (LPCTSTR)strPath, lpszTerminalNo,
  3182. stLocal.wYear, stLocal.wMonth, stLocal.wDay,
  3183. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3184. strcat_s(fileName, EXT_EVTLOG_NAME);
  3185. strcpy_s(szEvtxFileName, MAX_PATH, fileName);
  3186. Dbg("Combined EventLog FilePah: %s", szEvtxFileName);
  3187. return strlen(szEvtxFileName);
  3188. #endif
  3189. }
  3190. DWORD ResourceWatcherFSM::CalSpecifiedSecondsFrom1970(const WORD wDuration
  3191. , DWORD* dwStartTime
  3192. , DWORD* dwEndTime
  3193. , const PULONGLONG pStartTime
  3194. , const PULONGLONG pEndTime)
  3195. {
  3196. DWORD status = E_FAIL;
  3197. if (dwStartTime == NULL || dwEndTime == NULL)
  3198. return E_INVALIDARG;
  3199. if (wDuration == DURATION_NONE) {
  3200. *dwStartTime = *dwEndTime = 0;
  3201. return ERROR_SUCCESS;
  3202. }
  3203. ULONGLONG ullTimeStamp = 0;
  3204. ULONGLONG SecsTo1970 = 116444736000000000;
  3205. if (wDuration == DURAITON_CUSTOM) {
  3206. if (pStartTime == NULL || pEndTime == NULL)
  3207. return E_POINTER;
  3208. if (*pStartTime > *pEndTime)
  3209. return E_INVALIDARG;
  3210. ullTimeStamp = (*pStartTime) - SecsTo1970;
  3211. ullTimeStamp /= 10000000ULL;
  3212. *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3213. ullTimeStamp = (*pEndTime) - SecsTo1970;
  3214. ullTimeStamp /= 10000000ULL;
  3215. *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3216. return ERROR_SUCCESS;
  3217. }
  3218. SYSTEMTIME st;
  3219. GetSystemTime(&st);
  3220. FILETIME ftCurTime;
  3221. GetSystemTimeAsFileTime(&ftCurTime);
  3222. ULARGE_INTEGER uliCurTime, uliOffset, uliBackTime;
  3223. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  3224. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  3225. if (wDuration == DURATION_HOUR_ONE) {
  3226. uliOffset.QuadPart = UInt32x32To64(1 * 60 * 60, 1e7);
  3227. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3228. } else if (wDuration == DURATION_HOUR_TWELVE) {
  3229. uliOffset.QuadPart = UInt32x32To64(12 * 60 * 60, 1e7);
  3230. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3231. } else if (wDuration == DURATION_DAY_ONE) {
  3232. uliOffset.QuadPart = UInt32x32To64(24 * 60 * 60, 1e7);
  3233. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3234. } else if (wDuration == DURATION_DAY_SEVENT) {
  3235. uliOffset.QuadPart = UInt32x32To64(7 * 24 * 60 * 60, 1e7);
  3236. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3237. } else if (wDuration == DURATION_MONTH_ONE) {
  3238. uliOffset.QuadPart = UInt32x32To64(30 * 24 * 60 * 60, 1e7);
  3239. uliBackTime.QuadPart = uliCurTime.QuadPart - uliOffset.QuadPart;
  3240. } else {
  3241. Dbg("Unexpected duration paramter.");
  3242. return E_INVALIDARG;
  3243. }
  3244. ullTimeStamp = uliBackTime.QuadPart - SecsTo1970;
  3245. ullTimeStamp /= 10000000ULL;
  3246. *dwStartTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3247. ullTimeStamp = uliCurTime.QuadPart - SecsTo1970;
  3248. ullTimeStamp /= 10000000ULL;
  3249. *dwEndTime = (DWORD)(ullTimeStamp & 0xFFFFFFFF);
  3250. {
  3251. FILETIME ftBackTime;
  3252. SYSTEMTIME stUTC, stLocal;
  3253. ftBackTime.dwHighDateTime = uliBackTime.HighPart;
  3254. ftBackTime.dwLowDateTime = uliBackTime.LowPart;
  3255. FileTimeToSystemTime(&ftBackTime, &stUTC);
  3256. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  3257. CHAR szTimeFormat[MAX_PATH] = { 0 };
  3258. // Build a string showing the date and time.
  3259. sprintf_s(szTimeFormat, MAX_PATH, "%02d/%02d/%d %02d:%02d:%02d",
  3260. stLocal.wMonth, stLocal.wDay, stLocal.wYear,
  3261. stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3262. printf("Start time statmp: %s\n", szTimeFormat);
  3263. }
  3264. return ERROR_SUCCESS;
  3265. }
  3266. #endif //RVC_OS_WIN
  3267. BOOL ResourceWatcherFSM::ClearAd0Folder()
  3268. {
  3269. LOG_FUNCTION();
  3270. CSimpleStringA strAd0Path;
  3271. CSmartPointer<IConfigInfo> spConfigRun;
  3272. int nLastTaskTime(0);
  3273. CSimpleStringA ssFilePath(true);
  3274. ErrorCodeEnum ec = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  3275. spConfigRun->ReadConfigValueInt("LastClearTime", "Ad0Task", nLastTaskTime);
  3276. if(IsTodayDone(nLastTaskTime)) {
  3277. return TRUE;
  3278. }
  3279. ec = GetEntityBase()->GetFunction()->GetPath("Ad0", strAd0Path);
  3280. if(ec != Error_Succeed || strAd0Path.IsNullOrEmpty()) {
  3281. return FALSE;
  3282. }
  3283. if(!ExistsDirA(strAd0Path)) {
  3284. Dbg("The Folder(%s) is not existed", (LPCTSTR)strAd0Path);
  3285. spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
  3286. (const char*) CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  3287. return TRUE;
  3288. }
  3289. Dbg("Ad0Path: %s", (LPCTSTR)strAd0Path);
  3290. char displayTime[MAX_PATH] = {0};
  3291. ZeroMemory(&mftAd0RemoveTime, sizeof(FILETIME));
  3292. CalculateBackTime(&mftAd0RemoveTime, AD0_DAY_OF_BACKWARD);
  3293. GetTimeFormatStr(displayTime, MAX_PATH, &mftAd0RemoveTime);
  3294. Dbg("The date backward to delete: %s", displayTime);
  3295. #if defined(RVC_OS_WIN)
  3296. ssFilePath = strAd0Path + "\\*";
  3297. #else
  3298. ssFilePath = strAd0Path;
  3299. #endif //RVC_OS_WIN
  3300. int nDelSuc = 0;
  3301. int nDelFailed = 0;
  3302. int nfileSum = ClearSpecifieFile(DFT_Ad0, (LPCTSTR)ssFilePath, nDelSuc, nDelFailed);
  3303. Dbg("#Ad0#There are %d file(s), delete: %d, failed: %d.", nfileSum, nDelSuc, nDelFailed);
  3304. spConfigRun->WriteConfigValue("LastClearTime", "Ad0Task",
  3305. (const char*) CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  3306. return TRUE;
  3307. }
  3308. BOOL ResourceWatcherFSM::IsTodayDone(int nRecordTime)
  3309. {
  3310. if(nRecordTime <= 0) {
  3311. return FALSE;
  3312. }
  3313. SYSTEMTIME stNow = {};
  3314. SYSTEMTIME stTaskTime = CSmallDateTime(nRecordTime).ToSystemTime();
  3315. #if defined(_MSC_VER)
  3316. GetLocalTime(&stNow);
  3317. #else
  3318. stNow = CSmallDateTime::GetNow().ToSystemTime();
  3319. #endif //_MSC_VER
  3320. if (stTaskTime.wYear == stNow.wYear
  3321. && stTaskTime.wMonth == stNow.wMonth
  3322. && stTaskTime.wDay == stNow.wDay)
  3323. {
  3324. Dbg("task has been executed today, last clear time: %s",
  3325. (const char*)CSmallDateTime(nRecordTime).ToTimeString());
  3326. return TRUE;
  3327. } else {
  3328. Dbg("Last record time: %04d-%02d-%02d %02d:%02d:%02d",
  3329. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  3330. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond);
  3331. return FALSE;
  3332. }
  3333. }
  3334. BOOL ResourceWatcherFSM::GetSystemBootTime(CSmallDateTime& systemBootTime)
  3335. {
  3336. #if defined(RVC_OS_WIN)
  3337. PDH_STATUS Status;
  3338. HQUERY Query = NULL;
  3339. HCOUNTER hcElapsedTimeCount;
  3340. BOOL fSuc = FALSE;
  3341. Status = PdhOpenQuery(NULL, NULL, &Query);
  3342. PDH_FMT_COUNTERVALUE counterValue;
  3343. if (Status != ERROR_SUCCESS) {
  3344. Dbg("PdhOpenQuery failed with status 0x%x.", Status);
  3345. goto Cleanup;
  3346. }
  3347. Status = PdhAddCounter(Query, SystemElapsedQuery, NULL, &hcElapsedTimeCount);
  3348. if (Status != ERROR_SUCCESS) {
  3349. Dbg("PdhAddCounter for SystemElapsedQuery failed with status 0x%x.", Status);
  3350. goto Cleanup;
  3351. }
  3352. // 查询性能监视器数据
  3353. Status = PdhCollectQueryData(Query);
  3354. if (Status != ERROR_SUCCESS) {
  3355. Dbg("PdhCollectQueryData failed with 0x%x.", Status);
  3356. goto Cleanup;
  3357. }
  3358. Status = PdhGetFormattedCounterValue(hcElapsedTimeCount, PDH_FMT_LARGE, NULL, &counterValue);
  3359. if (Status == ERROR_SUCCESS) {
  3360. ULONGLONG ulSinceSeconds = counterValue.largeValue;
  3361. ULONG days = 0, hours = 0, minutes = 0, seconds = 0;
  3362. days = ULONG(ulSinceSeconds / DAY_DIV);
  3363. ulSinceSeconds %= DAY_DIV;
  3364. hours = ULONG(ulSinceSeconds / HOURS_DIV);
  3365. ulSinceSeconds %= HOURS_DIV;
  3366. minutes = ULONG(ulSinceSeconds / MINUS_DIV);
  3367. ulSinceSeconds %= MINUS_DIV;
  3368. seconds = ULONG(ulSinceSeconds);
  3369. Dbg("SystemElapseTime: %u:%02u:%02u:%02u", days, hours, minutes, seconds);
  3370. FILETIME ftCurTime, ftStartTime;
  3371. GetSystemTimeAsFileTime(&ftCurTime);
  3372. ULARGE_INTEGER uliCurTime;
  3373. uliCurTime.HighPart = ftCurTime.dwHighDateTime;
  3374. uliCurTime.LowPart = ftCurTime.dwLowDateTime;
  3375. //Dbg("%I64d", uliCurTime.QuadPart);
  3376. uliCurTime.QuadPart -= counterValue.largeValue * 1e7;
  3377. //Dbg("%I64d %I64d", uliCurTime.QuadPart, counterValue.largeValue);
  3378. ftStartTime.dwHighDateTime = uliCurTime.HighPart;
  3379. ftStartTime.dwLowDateTime = uliCurTime.LowPart;
  3380. //Dbg("%d %d %d %d", ftStartTime.dwHighDateTime, ftStartTime.dwLowDateTime,
  3381. // ftCurTime.dwHighDateTime, ftCurTime.dwLowDateTime);
  3382. SYSTEMTIME stUTC, stLocal;
  3383. FileTimeToSystemTime(&ftStartTime, &stUTC);
  3384. char temp[22];
  3385. SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
  3386. sprintf_s(temp, 22, "%d-%02d-%02d %02d:%02d:%02d",
  3387. stLocal.wYear, stLocal.wMonth, stLocal.wDay, stLocal.wHour, stLocal.wMinute, stLocal.wSecond);
  3388. Dbg("OSStartTime: %s", temp);
  3389. systemBootTime.FromSystemTime(stLocal);
  3390. fSuc = TRUE;
  3391. }
  3392. Cleanup:
  3393. Status = PdhRemoveCounter(hcElapsedTimeCount);
  3394. if (Query) {
  3395. PdhCloseQuery(Query);
  3396. }
  3397. return fSuc;
  3398. #else
  3399. DWORD ticks = 0;
  3400. SYSTEMTIME systemTime;
  3401. struct sysinfo info;
  3402. time_t curTime = 0;
  3403. time_t bootTime = 0;
  3404. struct tm* ptm = NULL;
  3405. if (sysinfo(&info)) {
  3406. Dbg("Failed to get sysinfo, errno:%u, reason:%s", errno, strerror(errno));
  3407. return FALSE;
  3408. }
  3409. time(&curTime);
  3410. if (curTime > info.uptime) {
  3411. bootTime = curTime - info.uptime;
  3412. } else {
  3413. bootTime = info.uptime - curTime;
  3414. }
  3415. ptm = localtime(&bootTime);
  3416. struct timespec ts;
  3417. if (!clock_gettime(CLOCK_MONOTONIC_RAW, &ts))
  3418. ticks = (ts.tv_sec * 1000) + (ts.tv_nsec / 1000000);
  3419. systemTime.wYear = (WORD)(ptm->tm_year + 1900);
  3420. systemTime.wMonth = (WORD)(ptm->tm_mon + 1);
  3421. systemTime.wDayOfWeek = (WORD)ptm->tm_wday;
  3422. systemTime.wDay = (WORD)ptm->tm_mday;
  3423. systemTime.wHour = (WORD)ptm->tm_hour;
  3424. systemTime.wMinute = (WORD)ptm->tm_min;
  3425. systemTime.wSecond = (WORD)ptm->tm_sec;
  3426. systemTime.wMilliseconds = (WORD)(ticks % 1000);
  3427. systemBootTime.FromSystemTime(systemTime);
  3428. Dbg("OSStartTime: %s", systemBootTime.ToTimeString().GetData());
  3429. return TRUE;
  3430. #endif //RVC_OS_WIN
  3431. }
  3432. #if defined(RVC_OS_WIN)
  3433. HRESULT ResourceWatcherFSM::SetDefaultAudioPlaybackDevice( LPCWSTR devID )
  3434. {
  3435. IPolicyConfigVista *pPolicyConfig;
  3436. ERole reserved = eConsole;
  3437. HRESULT hr = CoCreateInstance(__uuidof(CPolicyConfigVistaClient),
  3438. NULL, CLSCTX_ALL, __uuidof(IPolicyConfigVista), (LPVOID *)&pPolicyConfig);
  3439. if (SUCCEEDED(hr))
  3440. {
  3441. hr = pPolicyConfig->SetDefaultEndpoint(devID, reserved);
  3442. pPolicyConfig->Release();
  3443. }
  3444. return hr;
  3445. }
  3446. BOOL ResourceWatcherFSM::SetDefaultAudioDevice()
  3447. {
  3448. CSmartPointer<IEntityFunction> spFunction = GetEntityBase()->GetFunction();
  3449. CSmartPointer<IConfigInfo> spConfig;
  3450. CSimpleStringA strAudioName;
  3451. BOOL bRet = FALSE;
  3452. ErrorCodeEnum ec = spFunction->OpenConfig(Config_Root, spConfig);
  3453. if(ec != 0) {
  3454. Dbg("open root config failed!");
  3455. return FALSE;
  3456. }
  3457. ec = spConfig->ReadConfigValue("Audio", "handfree_out_dev", strAudioName);
  3458. if(strAudioName.IsNullOrEmpty()) {
  3459. Dbg("handfree_out_dev is nullptr or empty!!");
  3460. return FALSE;
  3461. }
  3462. Dbg("The hand_free_dev: %s", (LPCTSTR)strAudioName);
  3463. CSimpleStringW strwAudioName = CSimpleStringA2W(strAudioName);
  3464. HRESULT hr = CoInitialize(NULL);
  3465. if (SUCCEEDED(hr))
  3466. {
  3467. IMMDeviceEnumerator *pEnum = NULL;
  3468. // Create a multimedia device enumerator.
  3469. hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL,
  3470. CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pEnum);
  3471. if (SUCCEEDED(hr))
  3472. {
  3473. //判断是否是默认的音频设备,是就退出
  3474. bool bExit = false;
  3475. IMMDevice *pDefDevice = NULL;
  3476. hr = pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia,&pDefDevice);
  3477. if (SUCCEEDED(hr))
  3478. {
  3479. IPropertyStore *pStore;
  3480. hr = pDefDevice->OpenPropertyStore(STGM_READ, &pStore);
  3481. if (SUCCEEDED(hr))
  3482. {
  3483. PROPVARIANT friendlyName;
  3484. PropVariantInit(&friendlyName);
  3485. hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
  3486. if (SUCCEEDED(hr))
  3487. {
  3488. CSimpleStringW strTmp = friendlyName.pwszVal;
  3489. Dbg("default: %ws", (LPCWSTR)strTmp);
  3490. if(strTmp.IsStartWith(strwAudioName)) {
  3491. bExit = true;
  3492. }
  3493. PropVariantClear(&friendlyName);
  3494. }
  3495. pStore->Release();
  3496. }
  3497. pDefDevice->Release();
  3498. }
  3499. if (bExit) {
  3500. pEnum->Release();
  3501. return TRUE;
  3502. }
  3503. IMMDeviceCollection *pDevices;
  3504. // Enumerate the output devices.
  3505. hr = pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &pDevices);
  3506. if (SUCCEEDED(hr))
  3507. {
  3508. UINT count;
  3509. pDevices->GetCount(&count);
  3510. if (SUCCEEDED(hr))
  3511. {
  3512. for (int i = 0; i < count; i++)
  3513. {
  3514. bool bFind = false;
  3515. IMMDevice *pDevice;
  3516. hr = pDevices->Item(i, &pDevice);
  3517. if (SUCCEEDED(hr))
  3518. {
  3519. LPWSTR wstrID = NULL;
  3520. hr = pDevice->GetId(&wstrID);
  3521. if (SUCCEEDED(hr))
  3522. {
  3523. IPropertyStore *pStore;
  3524. hr = pDevice->OpenPropertyStore(STGM_READ, &pStore);
  3525. if (SUCCEEDED(hr))
  3526. {
  3527. PROPVARIANT friendlyName;
  3528. PropVariantInit(&friendlyName);
  3529. hr = pStore->GetValue(PKEY_Device_FriendlyName, &friendlyName);
  3530. if (SUCCEEDED(hr))
  3531. {
  3532. // if no options, print the device
  3533. // otherwise, find the selected device and set it to be default
  3534. CSimpleStringW strTmp = friendlyName.pwszVal;
  3535. Dbg("%d: %ws", i, (LPCWSTR)strTmp);
  3536. if(strTmp.IsStartWith(strwAudioName)) {
  3537. bFind = true;
  3538. HRESULT hr = SetDefaultAudioPlaybackDevice(wstrID);
  3539. if(SUCCEEDED(hr)) {
  3540. Dbg("set default audio player succ.");
  3541. bRet = TRUE;
  3542. } else {
  3543. Dbg("set default audio player failed");
  3544. }
  3545. }
  3546. PropVariantClear(&friendlyName);
  3547. }
  3548. pStore->Release();
  3549. }
  3550. }
  3551. pDevice->Release();
  3552. }
  3553. if (bFind)
  3554. {
  3555. break;
  3556. }
  3557. }
  3558. }
  3559. pDevices->Release();
  3560. }
  3561. pEnum->Release();
  3562. }
  3563. }
  3564. CoUninitialize();
  3565. return bRet;
  3566. }
  3567. #endif //RVC_OS_WIN
  3568. BOOL ResourceWatcherFSM::DetectIsFirstRunAtBoot()
  3569. {
  3570. LOG_FUNCTION();
  3571. CSystemRunInfo runInfo = { 0 };
  3572. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3573. BOOL bSet = FALSE;
  3574. CBootInfo bootInfo = { 0 };
  3575. CSmallDateTime dateTime;
  3576. Dbg("systemRunInfo time: %s", (LPCTSTR)runInfo.tmStart.ToTimeString());
  3577. ErrorCodeEnum erroCode = GetEntityBase()->GetFunction()->GetRebootInfo(/*runInfo.tmStart*/dateTime, bootInfo);
  3578. Dbg("bootInfor time: %s", (LPCTSTR)bootInfo.tmStart.ToTimeString());
  3579. CSmallDateTime systemBootTime;
  3580. BOOL bRet = GetSystemBootTime(systemBootTime);
  3581. if (bRet && systemBootTime > bootInfo.tmStart) {
  3582. ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
  3583. if (eRet != Error_Succeed) {
  3584. Dbg("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
  3585. }
  3586. bSet = TRUE;
  3587. } else {
  3588. GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
  3589. bSet = FALSE;
  3590. }
  3591. return bSet;
  3592. }