ResourceWatcherFSM.cpp 128 KB

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