CCMain.m 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCClientEncryption.h"
  37. #import "NCBridgeSwift.h"
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. tableMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. BOOL _loadingFolder;
  74. }
  75. @end
  76. @implementation CCMain
  77. #pragma --------------------------------------------------------------------------------------------
  78. #pragma mark ===== Init =====
  79. #pragma --------------------------------------------------------------------------------------------
  80. - (id)initWithCoder:(NSCoder *)aDecoder
  81. {
  82. if (self = [super initWithCoder:aDecoder]) {
  83. _directoryOrder = [CCUtility getOrderSettings];
  84. _directoryGroupBy = [CCUtility getGroupBySettings];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  90. }
  91. return self;
  92. }
  93. #pragma --------------------------------------------------------------------------------------------
  94. #pragma mark ===== View =====
  95. #pragma --------------------------------------------------------------------------------------------
  96. - (void)viewDidLoad
  97. {
  98. [super viewDidLoad];
  99. // init object
  100. _metadata = [tableMetadata new];
  101. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  102. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  104. _statusSwipeCell = [NSMutableDictionary new];
  105. _queueSelector = [NSMutableArray new];
  106. _isViewDidLoad = YES;
  107. _fatherPermission = @"";
  108. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  109. _searchResultMetadatas = [NSMutableArray new];
  110. _searchFileName = @"";
  111. _noFilesSearchTitle = @"";
  112. _noFilesSearchDescription = @"";
  113. // delegate
  114. self.tableView.delegate = self;
  115. self.tableView.tableFooterView = [UIView new];
  116. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  117. self.tableView.emptyDataSetDelegate = self;
  118. self.tableView.emptyDataSetSource = self;
  119. self.searchController.delegate = self;
  120. self.searchController.searchBar.delegate = self;
  121. [CCNetworking sharedNetworking].delegate = self;
  122. // Custom Cell
  123. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  125. // long press recognizer TableView
  126. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  127. [self.tableView addGestureRecognizer:longPressRecognizer];
  128. // Pull-to-Refresh
  129. [self createRefreshControl];
  130. // Register for 3D Touch Previewing if available
  131. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  132. {
  133. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  134. }
  135. // Back Button
  136. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  137. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  138. // reMenu Background
  139. _reMenuBackgroundView = [[UIView alloc] init];
  140. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  141. // if this is not Main (the Main uses inizializeMain)
  142. if (_isRoot == NO && app.activeAccount.length > 0) {
  143. // Settings this folder & delegate & Loading datasource
  144. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  145. // Load Datasource
  146. [self reloadDatasource:_serverUrl];
  147. // Read (File) Folder
  148. [self readFileReloadFolder];
  149. }
  150. // Title
  151. [self setTitle];
  152. // Search
  153. self.definesPresentationContext = YES;
  154. self.searchController.searchResultsUpdater = self;
  155. self.searchController.dimsBackgroundDuringPresentation = NO;
  156. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  157. [self.searchController.searchBar sizeToFit];
  158. self.searchController.searchBar.delegate = self;
  159. if (@available(iOS 11, *)) {
  160. self.navigationItem.searchController = self.searchController;
  161. self.navigationItem.hidesSearchBarWhenScrolling = true;
  162. self.navigationItem.searchController.searchBar.tintColor = [UIColor whiteColor];
  163. UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
  164. textField.textColor = [UIColor blackColor];
  165. textField.tintColor = [UIColor blackColor];
  166. UIView *backgroundView = textField.subviews.firstObject;
  167. backgroundView.backgroundColor = UIColor.whiteColor;
  168. backgroundView.layer.cornerRadius = 10;
  169. backgroundView.clipsToBounds = YES;
  170. } else {
  171. self.tableView.tableHeaderView = self.searchController.searchBar;
  172. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  173. }
  174. }
  175. // Apparirà
  176. - (void)viewWillAppear:(BOOL)animated
  177. {
  178. [super viewWillAppear:animated];
  179. // test
  180. if (app.activeAccount.length == 0)
  181. return;
  182. // Settings this folder & delegate & Loading datasource
  183. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  184. [CCNetworking sharedNetworking].delegate = self;
  185. // Color
  186. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  187. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  188. if (_isSelectedMode)
  189. [self setUINavigationBarSelected];
  190. else
  191. [self setUINavigationBarDefault];
  192. // If not editing mode remove _selectedFileIDs
  193. if (!self.tableView.editing)
  194. [_selectedFileIDsMetadatas removeAllObjects];
  195. // Plus Button
  196. [app plusButtonVisibile:true];
  197. }
  198. // E' arrivato
  199. - (void)viewDidAppear:(BOOL)animated
  200. {
  201. [super viewDidAppear:animated];
  202. // Active Main
  203. app.activeMain = self;
  204. // Test viewDidLoad
  205. if (_isViewDidLoad) {
  206. _isViewDidLoad = NO;
  207. } else {
  208. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  209. // Load Datasource
  210. [self reloadDatasource:_serverUrl];
  211. // Read (file) Folder
  212. [self readFileReloadFolder];
  213. }
  214. }
  215. // Title
  216. [self setTitle];
  217. }
  218. - (void)viewWillDisappear:(BOOL)animated
  219. {
  220. [super viewWillDisappear:animated];
  221. [self closeAllMenu];
  222. }
  223. - (void)didReceiveMemoryWarning
  224. {
  225. [super didReceiveMemoryWarning];
  226. // Dispose of any resources that can be recreated.
  227. }
  228. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  229. {
  230. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  231. [self closeAllMenu];
  232. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  233. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  234. // Portrait
  235. } else {
  236. // Landscape
  237. }
  238. [self.tableView reloadData];
  239. }];
  240. }
  241. - (BOOL)prefersStatusBarHidden
  242. {
  243. return NO;
  244. }
  245. // detect scroll for remove keyboard in search mode
  246. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  247. {
  248. if (_isSearchMode && scrollView == self.tableView) {
  249. [self.searchController.searchBar endEditing:YES];
  250. }
  251. }
  252. - (void)changeTheming
  253. {
  254. if (self.isViewLoaded && self.view.window)
  255. [app changeTheming:self];
  256. // Refresh control
  257. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  258. // Reload Table View
  259. [self tableViewReloadData];
  260. }
  261. #pragma --------------------------------------------------------------------------------------------
  262. #pragma mark ===== Initizlize Mail =====
  263. #pragma --------------------------------------------------------------------------------------------
  264. - (void)initializeMain:(NSNotification *)notification
  265. {
  266. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  267. _directoryGroupBy = nil;
  268. _directoryOrder = nil;
  269. _dateReadDataSource = nil;
  270. // test
  271. if (app.activeAccount.length == 0)
  272. return;
  273. if ([app.listMainVC count] == 0 || _isRoot) {
  274. // This is Root home main add list
  275. appDelegate.homeMain = self;
  276. _isRoot = YES;
  277. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  278. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  279. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  280. // go Home
  281. [self.navigationController popToRootViewControllerAnimated:NO];
  282. // setting Networking
  283. [CCNetworking sharedNetworking].delegate = self;
  284. [[CCNetworking sharedNetworking] settingAccount];
  285. // Remove search mode
  286. [self cancelSearchBar];
  287. // populate shared Link & User
  288. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  289. if (results) {
  290. appDelegate.sharesLink = results[0];
  291. appDelegate.sharesUserAndGroup = results[1];
  292. }
  293. // Load Datasource
  294. [self reloadDatasource:_serverUrl];
  295. // Read (File) Folder
  296. [self readFileReloadFolder];
  297. // Setting Theming
  298. [app settingThemingColorBrand];
  299. // Load photo datasorce
  300. if (appDelegate.activePhotos)
  301. [appDelegate.activePhotos reloadDatasourceForced];
  302. // remove all of detail
  303. if (appDelegate.activeDetail)
  304. [appDelegate.activeDetail removeAllView];
  305. // remove all Notification Messages
  306. [appDelegate.listOfNotifications removeAllObjects];
  307. // Not Photos Video in library ? then align
  308. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", app.activeAccount]];
  309. if ([recordsPhotoLibrary count] == 0) {
  310. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  311. }
  312. // Initializations
  313. [appDelegate applicationInitialized];
  314. } else {
  315. // reload datasource
  316. [self reloadDatasource:_serverUrl];
  317. }
  318. }
  319. #pragma --------------------------------------------------------------------------------------------
  320. #pragma mark ==== DZNEmptyDataSetSource ====
  321. #pragma --------------------------------------------------------------------------------------------
  322. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  323. {
  324. if (_loadingFolder)
  325. return NO;
  326. else
  327. return YES;
  328. }
  329. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  330. {
  331. return [UIColor whiteColor];
  332. }
  333. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  334. {
  335. if (_isSearchMode)
  336. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  337. else
  338. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  339. }
  340. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  341. {
  342. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  343. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  344. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  345. activityView.color = [NCBrandColor sharedInstance].brand;
  346. [activityView startAnimating];
  347. return activityView;
  348. }
  349. return nil;
  350. }
  351. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  352. {
  353. NSString *text;
  354. if (_isSearchMode) {
  355. text = _noFilesSearchTitle;
  356. } else {
  357. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  358. }
  359. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  360. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  361. }
  362. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  363. {
  364. NSString *text;
  365. if (_isSearchMode) {
  366. text = _noFilesSearchDescription;
  367. } else {
  368. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  369. }
  370. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  371. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  372. paragraph.alignment = NSTextAlignmentCenter;
  373. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  374. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  375. }
  376. #pragma --------------------------------------------------------------------------------------------
  377. #pragma mark ===== Text Field =====
  378. #pragma --------------------------------------------------------------------------------------------
  379. - (void)minCharTextFieldDidChange:(UITextField *)sender
  380. {
  381. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  382. if (alertController)
  383. {
  384. UITextField *fileName = alertController.textFields.firstObject;
  385. UIAlertAction *okAction = alertController.actions.lastObject;
  386. okAction.enabled = fileName.text.length > 0;
  387. }
  388. }
  389. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  390. [textField selectAll:textField];
  391. }
  392. #pragma --------------------------------------------------------------------------------------------
  393. #pragma mark ===== Graphic Window =====
  394. #pragma --------------------------------------------------------------------------------------------
  395. - (void)createRefreshControl
  396. {
  397. _refreshControl = [UIRefreshControl new];
  398. if (@available(iOS 11.0, *)) {
  399. [self.tableView setRefreshControl:_refreshControl];
  400. _refreshControl.tintColor = [UIColor whiteColor];
  401. } else {
  402. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  403. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  404. [self setRefreshControl:_refreshControl];
  405. }
  406. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  407. }
  408. - (void)deleteRefreshControl
  409. {
  410. [_refreshControl endRefreshing];
  411. self.refreshControl = nil;
  412. }
  413. - (void)refreshControlTarget
  414. {
  415. [self readFolder:_serverUrl];
  416. // Actuate `Peek` feedback (weak boom)
  417. AudioServicesPlaySystemSound(1519);
  418. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  419. }
  420. - (void)setTitle
  421. {
  422. // Color text self.navigationItem.title
  423. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  424. if (_isSelectedMode) {
  425. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  426. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  427. self.navigationItem.titleView = nil;
  428. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  429. } else {
  430. // we are in home : LOGO BRAND
  431. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  432. self.navigationItem.title = nil;
  433. if ([app.reachability isReachable] == NO)
  434. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  435. else
  436. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  437. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  438. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  439. [singleTap setNumberOfTapsRequired:1];
  440. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  441. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  442. } else {
  443. self.navigationItem.title = _titleMain;
  444. }
  445. }
  446. }
  447. /*
  448. - (UIStatusBarStyle)preferredStatusBarStyle
  449. {
  450. UIBarStyle barStyle = self.navigationController.navigationBar.barStyle;
  451. if (barStyle == UIStatusBarStyleLightContent)
  452. return UIStatusBarStyleDefault;
  453. else
  454. return UIStatusBarStyleLightContent;
  455. }
  456. */
  457. - (void)setUINavigationBarDefault
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  460. UIBarButtonItem *buttonMore, *buttonNotification;
  461. // =
  462. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  463. buttonMore.enabled = true;
  464. // <
  465. self.navigationController.navigationBar.hidden = NO;
  466. // Notification
  467. if ([app.listOfNotifications count] > 0) {
  468. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  469. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  470. buttonNotification.enabled = true;
  471. }
  472. if (buttonNotification)
  473. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  474. else
  475. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  476. self.navigationItem.leftBarButtonItem = nil;
  477. }
  478. - (void)setUINavigationBarSelected
  479. {
  480. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  481. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  482. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  483. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  484. self.navigationItem.leftBarButtonItem = leftButton;
  485. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  486. }
  487. - (void)cancelSelect
  488. {
  489. [self tableViewSelect:NO];
  490. [app.reSelectMenu close];
  491. }
  492. - (void)closeAllMenu
  493. {
  494. // close Menu
  495. [app.reSelectMenu close];
  496. [app.reMainMenu close];
  497. // Close Menu Logo
  498. [CCMenuAccount dismissMenu];
  499. }
  500. #pragma --------------------------------------------------------------------------------------------
  501. #pragma mark ===== Document Picker =====
  502. #pragma --------------------------------------------------------------------------------------------
  503. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  504. {
  505. NSLog(@"Cancelled");
  506. }
  507. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  508. {
  509. NSLog(@"Cancelled");
  510. }
  511. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  512. {
  513. documentPicker.delegate = self;
  514. [self presentViewController:documentPicker animated:YES completion:nil];
  515. }
  516. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  517. {
  518. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  519. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  520. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  521. __block NSError *error;
  522. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  523. NSString *fileName = [url lastPathComponent];
  524. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  525. NSData *data = [NSData dataWithContentsOfURL:newURL];
  526. if (data && error == nil) {
  527. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  528. // Upload File
  529. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  530. } else {
  531. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  532. }
  533. } else {
  534. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  535. }
  536. }];
  537. }
  538. }
  539. - (void)openImportDocumentPicker
  540. {
  541. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  542. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  543. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  544. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  545. documentProviderMenu.delegate = self;
  546. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  547. }
  548. #pragma --------------------------------------------------------------------------------------------
  549. #pragma mark ===== Assets Picker =====
  550. #pragma --------------------------------------------------------------------------------------------
  551. -(void)dismissFormUploadAssets
  552. {
  553. [self reloadDatasource];
  554. }
  555. - (void)openAssetsPickerController
  556. {
  557. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  558. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  559. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  560. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  561. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  562. [app aspectNavigationControllerBar:navBar online:YES hidden:NO];
  563. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  564. dispatch_async(dispatch_get_main_queue(), ^{
  565. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  566. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  567. // init picker
  568. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  569. // set delegate
  570. picker.delegate = self;
  571. // to show selection order
  572. //picker.showsSelectionIndex = YES;
  573. // to present picker as a form sheet in iPad
  574. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  575. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  576. // present picker
  577. [self presentViewController:picker animated:YES completion:nil];
  578. });
  579. }];
  580. }
  581. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  582. {
  583. if (picker.selectedAssets.count > k_pickerControllerMax) {
  584. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  585. return NO;
  586. }
  587. return YES;
  588. }
  589. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  590. {
  591. [picker dismissViewControllerAnimated:YES completion:^{
  592. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  593. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  594. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  595. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  596. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  597. [self presentViewController:navigationController animated:YES completion:nil];
  598. }];
  599. }
  600. // New folder or new photo or video
  601. - (void)returnCreate:(NSInteger)type
  602. {
  603. switch (type) {
  604. case k_returnCreateFolderPlain: {
  605. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  606. NSString *message;
  607. UIAlertController *alertController;
  608. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  609. message = @"/";
  610. } else {
  611. message = [serverUrl lastPathComponent];
  612. }
  613. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  614. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  615. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  616. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  617. }];
  618. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  619. NSLog(@"Cancel action");
  620. }];
  621. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  622. UITextField *fileName = alertController.textFields.firstObject;
  623. [self createFolder:fileName.text serverUrl:serverUrl];
  624. }];
  625. okAction.enabled = NO;
  626. [alertController addAction:cancelAction];
  627. [alertController addAction:okAction];
  628. [self presentViewController:alertController animated:YES completion:nil];
  629. }
  630. break;
  631. case k_returnCreateFotoVideoPlain: {
  632. [self openAssetsPickerController];
  633. }
  634. break;
  635. case k_returnCreateFilePlain: {
  636. [self openImportDocumentPicker];
  637. }
  638. break;
  639. case k_returnCreateFotoVideoEncrypted: {
  640. [self openAssetsPickerController];
  641. }
  642. break;
  643. case k_returnCreateFileEncrypted: {
  644. [self openImportDocumentPicker];
  645. }
  646. break;
  647. case k_returnCreateFileText: {
  648. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  649. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  650. [self presentViewController:navigationController animated:YES completion:nil];
  651. }
  652. break;
  653. }
  654. }
  655. #pragma --------------------------------------------------------------------------------------------
  656. #pragma mark ===== Save selected File =====
  657. #pragma --------------------------------------------------------------------------------------------
  658. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  659. {
  660. if (error)
  661. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  662. else
  663. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  664. }
  665. - (void)saveSelectedFiles
  666. {
  667. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  668. return;
  669. NSLog(@"[LOG] Start download selected files ...");
  670. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  671. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  672. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  673. for (tableMetadata *metadata in metadatas) {
  674. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  675. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  676. if (serverUrl)
  677. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  678. }
  679. }
  680. [_hud hideHud];
  681. });
  682. [self tableViewSelect:NO];
  683. }
  684. #pragma --------------------------------------------------------------------------------------------
  685. #pragma mark === Delegate Login ===
  686. #pragma --------------------------------------------------------------------------------------------
  687. - (void)loginSuccess:(NSInteger)loginType
  688. {
  689. [self readFolder:_serverUrl];
  690. }
  691. - (void)loginDisappear
  692. {
  693. app.activeLogin = nil;
  694. }
  695. #pragma mark -
  696. #pragma --------------------------------------------------------------------------------------------
  697. #pragma mark ===== Peek & Pop =====
  698. #pragma --------------------------------------------------------------------------------------------
  699. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  700. {
  701. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  702. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  703. if (metadata.thumbnailExists) {
  704. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  705. if (cell) {
  706. previewingContext.sourceRect = cell.frame;
  707. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  708. vc.delegate = self;
  709. vc.metadata = metadata;
  710. return vc;
  711. }
  712. }
  713. return nil;
  714. }
  715. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  716. {
  717. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  718. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  719. }
  720. #pragma mark -
  721. #pragma --------------------------------------------------------------------------------------------
  722. #pragma mark ==== External Sites ====
  723. #pragma --------------------------------------------------------------------------------------------
  724. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  725. {
  726. [[NCManageDatabase sharedInstance] deleteExternalSites];
  727. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  728. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  729. }
  730. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  731. {
  732. NSString *error = [NSString stringWithFormat:@"Get external site failure error %lu, %@", (long)errorCode, message];
  733. NSLog(@"[LOG] %@", error);
  734. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  735. }
  736. #pragma --------------------------------------------------------------------------------------------
  737. #pragma mark ==== Activity ====
  738. #pragma --------------------------------------------------------------------------------------------
  739. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  740. {
  741. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  742. // Reload Activity Data Source
  743. [app.activeActivity reloadDatasource];
  744. }
  745. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  746. {
  747. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %lu, %@", (long)errorCode, message];
  748. NSLog(@"[LOG] %@", error);
  749. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  750. }
  751. #pragma --------------------------------------------------------------------------------------------
  752. #pragma mark ==== Notification ====
  753. #pragma --------------------------------------------------------------------------------------------
  754. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  755. {
  756. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  757. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  758. // Order by date
  759. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  760. OCNotifications *notification1 = obj1, *notification2 = obj2;
  761. return [notification2.date compare: notification1.date];
  762. }];
  763. // verify if listOfNotifications is changed
  764. NSString *old = @"", *new = @"";
  765. for (OCNotifications *notification in listOfNotifications)
  766. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  767. for (OCNotifications *notification in appDelegate.listOfNotifications)
  768. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  769. if (![new isEqualToString:old]) {
  770. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  771. // reload Notification view
  772. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  773. }
  774. // Update NavigationBar
  775. if (!_isSelectedMode) {
  776. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  777. }
  778. });
  779. }
  780. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  781. {
  782. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %lu, %@", (long)errorCode, message];
  783. NSLog(@"[LOG] %@", error);
  784. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  785. // Update NavigationBar
  786. if (!_isSelectedMode)
  787. [self setUINavigationBarDefault];
  788. }
  789. - (void)viewNotification
  790. {
  791. if ([app.listOfNotifications count] > 0) {
  792. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  793. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  794. [self presentViewController:notificationVC animated:YES completion:nil];
  795. }
  796. }
  797. #pragma --------------------------------------------------------------------------------------------
  798. #pragma mark ==== User Profile ====
  799. #pragma --------------------------------------------------------------------------------------------
  800. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  801. {
  802. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %lu, %@", (long)errorCode, message];
  803. NSLog(@"[LOG] %@", error);
  804. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  805. }
  806. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  807. {
  808. // Update User (+ userProfile.id)
  809. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  810. // Get Account Active
  811. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  812. // Setting App active account
  813. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  814. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  815. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  816. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  817. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  818. if (avatar)
  819. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  820. else
  821. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  822. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  823. });
  824. }
  825. #pragma --------------------------------------------------------------------------------------------
  826. #pragma mark ==== Capabilities ====
  827. #pragma --------------------------------------------------------------------------------------------
  828. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  829. {
  830. // Unauthorized
  831. if (errorCode == kOCErrorServerUnauthorized)
  832. [app openLoginView:self loginType:loginModifyPasswordUser];
  833. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %lu, %@", (long)errorCode, message];
  834. NSLog(@"[LOG] %@", error);
  835. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  836. // Change Theming color
  837. [app settingThemingColorBrand];
  838. }
  839. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  840. {
  841. // Update capabilities db
  842. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  843. // ------ THEMING -----------------------------------------------------------------------
  844. // Download Theming Background & Change Theming color
  845. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  846. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  847. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  848. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  849. if (themingBackground)
  850. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  851. else
  852. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  853. }
  854. dispatch_async(dispatch_get_main_queue(), ^{
  855. [app settingThemingColorBrand];
  856. });
  857. });
  858. // ------ SEARCH ------------------------------------------------------------------------
  859. // Search bar if change version
  860. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  861. [self cancelSearchBar];
  862. }
  863. // ------ GET SERVICE SERVER ------------------------------------------------------------
  864. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  865. // Read External Sites
  866. if (capabilities.isExternalSitesServerEnabled) {
  867. metadataNet.action = actionGetExternalSitesServer;
  868. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  869. }
  870. // Read Share
  871. if (capabilities.isFilesSharingAPIEnabled) {
  872. [app.sharesID removeAllObjects];
  873. metadataNet.action = actionReadShareServer;
  874. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  875. }
  876. // Read Notification
  877. metadataNet.action = actionGetNotificationServer;
  878. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  879. // Read User Profile
  880. metadataNet.action = actionGetUserProfile;
  881. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  882. // Read Activity
  883. metadataNet.action = actionGetActivityServer;
  884. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  885. }
  886. #pragma mark -
  887. #pragma --------------------------------------------------------------------------------------------
  888. #pragma mark ==== Request Server Information ====
  889. #pragma --------------------------------------------------------------------------------------------
  890. - (void)requestServerCapabilities
  891. {
  892. // test
  893. if (app.activeAccount.length == 0)
  894. return;
  895. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  896. metadataNet.action = actionGetCapabilities;
  897. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  898. }
  899. #pragma mark -
  900. #pragma --------------------------------------------------------------------------------------------
  901. #pragma mark ==== Middleware Ping ====
  902. #pragma --------------------------------------------------------------------------------------------
  903. - (void)middlewarePing
  904. {
  905. // test
  906. if (app.activeAccount.length == 0)
  907. return;
  908. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  909. metadataNet.action = actionMiddlewarePing;
  910. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  911. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  912. }
  913. #pragma mark -
  914. #pragma --------------------------------------------------------------------------------------------
  915. #pragma mark ==== Download Thumbnail Delegate ====
  916. #pragma --------------------------------------------------------------------------------------------
  917. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  918. {
  919. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  920. }
  921. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  922. {
  923. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  924. if ([self indexPathIsValid:indexPath]) {
  925. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  926. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  927. }
  928. }
  929. #pragma --------------------------------------------------------------------------------------------
  930. #pragma mark ==== Download ====
  931. #pragma --------------------------------------------------------------------------------------------
  932. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  933. {
  934. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  935. // File do not exists on server, remove in local
  936. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  937. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  938. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  939. if (metadata.directory && serverUrl) {
  940. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  941. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  942. }
  943. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  944. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  945. }
  946. if ([selector isEqualToString:selectorLoadViewImage]) {
  947. dispatch_async(dispatch_get_main_queue(), ^{
  948. // Updating Detail
  949. if (app.activeDetail)
  950. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  951. // Updating Photos
  952. if (app.activePhotos)
  953. [app.activePhotos downloadFileFailure:errorCode];
  954. });
  955. } else {
  956. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  957. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  958. }
  959. [self reloadDatasource:serverUrl];
  960. }
  961. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  962. {
  963. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  964. if (metadata == nil)
  965. return;
  966. // Download
  967. if ([selector isEqualToString:selectorDownloadFile]) {
  968. [self reloadDatasource:serverUrl];
  969. }
  970. // Synchronized
  971. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  972. [self reloadDatasource:serverUrl];
  973. }
  974. // add Favorite
  975. if ([selector isEqualToString:selectorAddFavorite]) {
  976. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  977. }
  978. // open View File
  979. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  980. [self reloadDatasource:serverUrl];
  981. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  982. selector = selectorOpenIn;
  983. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  984. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  985. selector = selectorOpenIn;
  986. } else {
  987. _metadata = metadata;
  988. if ([self shouldPerformSegue])
  989. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  990. }
  991. }
  992. // Open with...
  993. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  994. [self reloadDatasource:serverUrl];
  995. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  996. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  997. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName]];
  998. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  999. _docController.delegate = self;
  1000. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1001. }
  1002. // Save to Photo Album
  1003. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1004. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1005. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1006. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1007. if (image)
  1008. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1009. else
  1010. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1011. }
  1012. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1013. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1014. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName])) {
  1015. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1016. } else {
  1017. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1018. }
  1019. }
  1020. [self reloadDatasource:serverUrl];
  1021. }
  1022. // Copy File
  1023. if ([selector isEqualToString:selectorLoadCopy]) {
  1024. [self reloadDatasource:serverUrl];
  1025. [self copyFileToPasteboard:metadata];
  1026. }
  1027. //download file plist
  1028. if ([selector isEqualToString:selectorLoadPlist]) {
  1029. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1030. long countSelectorLoadPlist = 0;
  1031. for (NSOperation *operation in [app.netQueue operations]) {
  1032. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1033. countSelectorLoadPlist++;
  1034. }
  1035. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1036. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1037. dispatch_async(dispatch_get_main_queue(), ^{
  1038. [self reloadDatasource:serverUrl];
  1039. });
  1040. }
  1041. });
  1042. }
  1043. //selectorLoadViewImage
  1044. if ([selector isEqualToString:selectorLoadViewImage]) {
  1045. // Detail
  1046. if (app.activeDetail)
  1047. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1048. // Photos
  1049. if (app.activePhotos)
  1050. [app.activePhotos downloadFileSuccess:metadata];
  1051. [self reloadDatasource:serverUrl];
  1052. }
  1053. // if exists postselector call self with selectorPost
  1054. if ([selectorPost length] > 0)
  1055. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1056. // Auto Download Upload
  1057. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1058. // ONLY BACKGROUND
  1059. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1060. } else {
  1061. // ONLY FOREFROUND
  1062. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1063. }
  1064. }
  1065. - (void)downloadSelectedFilesFolders
  1066. {
  1067. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1068. return;
  1069. NSLog(@"[LOG] Start download selected ...");
  1070. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1071. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1072. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1073. for (tableMetadata *metadata in selectedMetadatas) {
  1074. if (metadata.directory) {
  1075. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1076. if (serverUrl) {
  1077. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1078. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1079. }
  1080. } else {
  1081. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1082. }
  1083. }
  1084. [_hud hideHud];
  1085. });
  1086. [self tableViewSelect:NO];
  1087. }
  1088. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1089. {
  1090. }
  1091. #pragma --------------------------------------------------------------------------------------------
  1092. #pragma mark ===== Upload new Photos/Videos =====
  1093. #pragma --------------------------------------------------------------------------------------------
  1094. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1095. {
  1096. // Auto Download Upload
  1097. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1098. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1099. // Change priority Auto Upload
  1100. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1101. // Activity
  1102. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1103. }
  1104. if (errorCode != kCFURLErrorCancelled)
  1105. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1106. } else {
  1107. // Delete record on Table Auto Upload
  1108. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1109. // Activity
  1110. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Too many error, file deleted" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1111. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1112. }
  1113. } else {
  1114. // Read File test do not exists
  1115. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1116. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1117. // reUpload
  1118. if (metadata)
  1119. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1120. }
  1121. // Print error
  1122. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1123. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1124. }
  1125. }
  1126. [self reloadDatasource:serverUrl];
  1127. }
  1128. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1129. {
  1130. // Auto Download Upload
  1131. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1132. // ONLY BACKGROUND
  1133. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1134. } else {
  1135. // ONLY FOREFROUND
  1136. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1137. }
  1138. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1139. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1140. [self readFolder:serverUrl];
  1141. } else {
  1142. [self reloadDatasource:serverUrl];
  1143. }
  1144. });
  1145. }
  1146. //
  1147. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1148. //
  1149. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1150. {
  1151. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1152. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1153. });
  1154. }
  1155. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1156. {
  1157. NSArray *assets = [arguments objectAtIndex:0];
  1158. NSString *serverUrl = [arguments objectAtIndex:1];
  1159. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1160. NSString *session = [arguments objectAtIndex:3];
  1161. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1162. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1163. if (!directoryID) return;
  1164. // if request create the folder for Photos & the subfolders
  1165. if ([autoUploadPath isEqualToString:serverUrl])
  1166. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1167. return;
  1168. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1169. for (PHAsset *asset in assets) {
  1170. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1171. NSDate *assetDate = asset.creationDate;
  1172. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1173. // Create serverUrl if use sub folder
  1174. if (useSubFolder) {
  1175. [formatter setDateFormat:@"yyyy"];
  1176. NSString *yearString = [formatter stringFromDate:assetDate];
  1177. [formatter setDateFormat:@"MM"];
  1178. NSString *monthString = [formatter stringFromDate:assetDate];
  1179. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1180. }
  1181. // Check if is in upload
  1182. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1183. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1184. if ([isRecordInSessions count] > 0) {
  1185. // next upload
  1186. continue;
  1187. } else {
  1188. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1189. metadataNet.action = actionReadFile;
  1190. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1191. metadataNet.fileName = fileName;
  1192. metadataNet.session = session;
  1193. metadataNet.selector = selectorReadFileUploadFile;
  1194. metadataNet.serverUrl = serverUrl;
  1195. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1196. }
  1197. }
  1198. }
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. #pragma mark ==== Read File ====
  1201. #pragma --------------------------------------------------------------------------------------------
  1202. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1203. {
  1204. // Unauthorized
  1205. if (errorCode == kOCErrorServerUnauthorized)
  1206. [app openLoginView:self loginType:loginModifyPasswordUser];
  1207. // UploadFile
  1208. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1209. // File not exists
  1210. if (errorCode == 404) {
  1211. metadataNet.errorCode = 0;
  1212. metadataNet.selector = selectorUploadFile;
  1213. metadataNet.selectorPost = nil;
  1214. metadataNet.taskStatus = k_taskStatusResume;
  1215. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1216. } else {
  1217. // error ho many retry befor notification and go to on next asses
  1218. if (metadataNet.errorRetry < 3) {
  1219. // Retry read file
  1220. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1221. } else {
  1222. // STOP check file, view message error
  1223. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1224. }
  1225. }
  1226. }
  1227. }
  1228. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1229. {
  1230. // Read Folder
  1231. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1232. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1233. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1234. [self readFolder:metadataNet.serverUrl];
  1235. }
  1236. }
  1237. // UploadFile
  1238. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1239. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1240. metadataNet.selector = selectorUploadFile;
  1241. metadataNet.selectorPost = nil;
  1242. metadataNet.taskStatus = k_taskStatusResume;
  1243. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1244. }
  1245. }
  1246. - (void)readFileReloadFolder
  1247. {
  1248. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1249. return;
  1250. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1251. metadataNet.action = actionReadFile;
  1252. metadataNet.priority = NSOperationQueuePriorityHigh;
  1253. metadataNet.selector = selectorReadFileReloadFolder;
  1254. metadataNet.serverUrl = _serverUrl;
  1255. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1256. }
  1257. #pragma --------------------------------------------------------------------------------------------
  1258. #pragma mark ==== Read Folder ====
  1259. #pragma --------------------------------------------------------------------------------------------
  1260. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1261. {
  1262. // stoprefresh
  1263. [_refreshControl endRefreshing];
  1264. // Unauthorized
  1265. if (errorCode == kOCErrorServerUnauthorized)
  1266. [app openLoginView:self loginType:loginModifyPasswordUser];
  1267. _loadingFolder = NO;
  1268. [self tableViewReloadData];
  1269. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1270. // verify active user
  1271. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1272. if (message && [record.account isEqualToString:metadataNet.account])
  1273. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1274. [self reloadDatasource:metadataNet.serverUrl];
  1275. }
  1276. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1277. {
  1278. // stoprefresh
  1279. [_refreshControl endRefreshing];
  1280. // verify active user
  1281. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1282. if (![record.account isEqualToString:metadataNet.account])
  1283. return;
  1284. // save father e update permission
  1285. if(!_isSearchMode && metadataFolder)
  1286. _fatherPermission = metadataFolder.permissions;
  1287. NSArray *recordsInSessions;
  1288. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1289. if (_isSearchMode) {
  1290. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1291. } else {
  1292. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1293. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1294. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1295. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1296. }
  1297. for (tableMetadata *metadata in metadatas) {
  1298. // verify if the record is in download/upload progress
  1299. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1300. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1301. // is in Download or Upload
  1302. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1303. continue;
  1304. }
  1305. }
  1306. // Insert in Array
  1307. [metadatasToInsertInDB addObject:metadata];
  1308. }
  1309. // insert in Database
  1310. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1311. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1312. // read plist
  1313. if (!_isSearchMode)
  1314. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1315. // File is changed ??
  1316. if (!_isSearchMode && metadatasToInsertInDB)
  1317. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1318. });
  1319. // Search Mode
  1320. if (_isSearchMode) {
  1321. // Fix managed -> Unmanaged _searchResultMetadatas
  1322. if (metadatasToInsertInDB)
  1323. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1324. [self reloadDatasource:metadataNet.serverUrl];
  1325. }
  1326. // this is the same directory
  1327. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1328. // reload
  1329. [self reloadDatasource:metadataNet.serverUrl];
  1330. // Enable change user
  1331. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1332. _loadingFolder = NO;
  1333. [self tableViewReloadData];
  1334. }
  1335. }
  1336. - (void)readFolder:(NSString *)serverUrl
  1337. {
  1338. // init control
  1339. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1340. [_refreshControl endRefreshing];
  1341. return;
  1342. }
  1343. // Search Mode
  1344. if (_isSearchMode) {
  1345. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1346. _searchFileName = @""; // forced reload searchg
  1347. [self updateSearchResultsForSearchController:self.searchController];
  1348. return;
  1349. }
  1350. _loadingFolder = YES;
  1351. [self tableViewReloadData];
  1352. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1353. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1354. metadataNet.action = actionReadFolder;
  1355. metadataNet.date = [NSDate date];
  1356. metadataNet.depth = @"1";
  1357. metadataNet.directoryID = directory.directoryID;
  1358. metadataNet.priority = NSOperationQueuePriorityHigh;
  1359. metadataNet.selector = selectorReadFolder;
  1360. metadataNet.serverUrl = serverUrl;
  1361. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1362. }
  1363. #pragma mark -
  1364. #pragma --------------------------------------------------------------------------------------------
  1365. #pragma mark ===== Search =====
  1366. #pragma --------------------------------------------------------------------------------------------
  1367. -(void)searchStartTimer
  1368. {
  1369. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1370. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1371. _noFilesSearchTitle = @"";
  1372. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1373. [self.tableView reloadEmptyDataSet];
  1374. }
  1375. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1376. {
  1377. //[self setNeedsStatusBarAppearanceUpdate];
  1378. _isSearchMode = YES;
  1379. [self deleteRefreshControl];
  1380. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1381. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1382. _searchFileName = fileName;
  1383. // First : filter
  1384. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1385. if (!directoryID) return;
  1386. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileName CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1387. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1388. [_searchResultMetadatas removeAllObjects];
  1389. for (tableMetadata *record in records)
  1390. [_searchResultMetadatas addObject:record];
  1391. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1392. metadataNet.account = app.activeAccount;
  1393. metadataNet.directoryID = directoryID;
  1394. metadataNet.selector = selectorSearch;
  1395. metadataNet.serverUrl = _serverUrl;
  1396. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1397. // Version >= 12
  1398. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1399. [_timerWaitInput invalidate];
  1400. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1401. }
  1402. }
  1403. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1404. [self reloadDatasource];
  1405. }
  1406. }
  1407. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1408. {
  1409. [self cancelSearchBar];
  1410. [self readFolder:_serverUrl];
  1411. }
  1412. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1413. {
  1414. // Unauthorized
  1415. if (errorCode == kOCErrorServerUnauthorized)
  1416. [app openLoginView:self loginType:loginModifyPasswordUser];
  1417. if (message && errorCode != kOCErrorServerUnauthorized)
  1418. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1419. _searchFileName = @"";
  1420. }
  1421. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1422. {
  1423. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1424. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1425. }
  1426. - (void)cancelSearchBar
  1427. {
  1428. if (self.searchController.active) {
  1429. [self.searchController setActive:NO];
  1430. [self createRefreshControl];
  1431. _isSearchMode = NO;
  1432. _searchFileName = @"";
  1433. _dateReadDataSource = nil;
  1434. _searchResultMetadatas = [NSMutableArray new];
  1435. [self reloadDatasource];
  1436. }
  1437. //[self setNeedsStatusBarAppearanceUpdate];
  1438. }
  1439. #pragma mark -
  1440. #pragma --------------------------------------------------------------------------------------------
  1441. #pragma mark ===== Delete File or Folder =====
  1442. #pragma --------------------------------------------------------------------------------------------
  1443. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1444. {
  1445. // Unauthorized
  1446. if (errorCode == kOCErrorServerUnauthorized)
  1447. [app openLoginView:self loginType:loginModifyPasswordUser];
  1448. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1449. [self deleteFileOrFolderSuccess:metadataNet];
  1450. }
  1451. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1452. {
  1453. [_queueSelector removeObject:metadataNet.selector];
  1454. if ([_queueSelector count] == 0) {
  1455. [_hud hideHud];
  1456. // next
  1457. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1458. if ([_selectedFileIDsMetadatas count] > 0) {
  1459. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1460. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1461. } else {
  1462. // End Select Table View
  1463. [self tableViewSelect:NO];
  1464. // Reload
  1465. if (_isSearchMode)
  1466. [self readFolder:metadataNet.serverUrl];
  1467. else
  1468. [self reloadDatasource:metadataNet.serverUrl];
  1469. }
  1470. }
  1471. }
  1472. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1473. {
  1474. [_queueSelector addObject:selectorDelete];
  1475. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1476. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1477. }
  1478. - (void)deleteFile
  1479. {
  1480. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1481. return;
  1482. [_queueSelector removeAllObjects];
  1483. if ([_selectedFileIDsMetadatas count] > 0) {
  1484. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1485. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1486. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1487. } else {
  1488. _numSelectedFileIDsMetadatas = 1;
  1489. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1490. }
  1491. }
  1492. #pragma --------------------------------------------------------------------------------------------
  1493. #pragma mark ===== Rename / Move =====
  1494. #pragma --------------------------------------------------------------------------------------------
  1495. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1496. {
  1497. [self readFolder:metadataNet.serverUrl];
  1498. }
  1499. - (void)renameFile:(NSArray *)arguments
  1500. {
  1501. tableMetadata* metadata = [arguments objectAtIndex:0];
  1502. NSString *fileName = [arguments objectAtIndex:1];
  1503. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1504. }
  1505. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1506. {
  1507. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1508. [_hud hideHud];
  1509. if (message && errorCode != kOCErrorServerUnauthorized)
  1510. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1511. // End Select Table View
  1512. [self tableViewSelect:NO];
  1513. // reload Datasource
  1514. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1515. [self readFolder:metadataNet.serverUrl];
  1516. else
  1517. [self reloadDatasource];
  1518. }
  1519. }
  1520. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1521. {
  1522. [_queueSelector removeObject:metadataNet.selector];
  1523. if ([_queueSelector count] == 0) {
  1524. [_hud hideHud];
  1525. NSString *fileName = metadataNet.fileName;
  1526. NSString *directoryID = metadataNet.directoryID;
  1527. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1528. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1529. if (!serverUrlTo) return;
  1530. // FILE -> Metadata
  1531. if (metadataNet.directory == NO)
  1532. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1533. // DIRECTORY -> Directory - CCMetadata
  1534. if (metadataNet.directory == YES) {
  1535. // delete all dir / subdir
  1536. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1537. // move metadata
  1538. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1539. // Add new directory
  1540. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1541. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1542. }
  1543. // next
  1544. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1545. if ([_selectedFileIDsMetadatas count] > 0) {
  1546. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1547. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1548. } else {
  1549. // End Select Table View
  1550. [self tableViewSelect:NO];
  1551. // reload Datasource
  1552. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1553. [self readFolder:metadataNet.serverUrl];
  1554. else
  1555. [self reloadDatasource];
  1556. }
  1557. }
  1558. }
  1559. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1560. {
  1561. tableMetadata *metadata = [arguments objectAtIndex:0];
  1562. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1563. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1564. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1565. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1566. if (!serverUrl) return;
  1567. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1568. if (!directoryIDTo) return;
  1569. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1570. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1571. if(!error) {
  1572. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1573. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1574. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1575. }];
  1576. [alert addAction:ok];
  1577. [self presentViewController:alert animated:YES completion:nil];
  1578. });
  1579. // End Select Table View
  1580. [self tableViewSelect:NO];
  1581. // reload Datasource
  1582. [self readFileReloadFolder];
  1583. return;
  1584. }
  1585. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1586. metadataNet.action = actionMoveFileOrFolder;
  1587. metadataNet.directory = metadata.directory;
  1588. metadataNet.fileID = metadata.fileID;
  1589. metadataNet.directoryID = metadata.directoryID;
  1590. metadataNet.directoryIDTo = directoryIDTo;
  1591. metadataNet.fileName = metadata.fileName;
  1592. metadataNet.fileNameTo = metadata.fileName;
  1593. metadataNet.etag = metadata.etag;
  1594. metadataNet.selector = selectorMove;
  1595. metadataNet.serverUrl = serverUrl;
  1596. metadataNet.serverUrlTo = serverUrlTo;
  1597. [_queueSelector addObject:metadataNet.selector];
  1598. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1599. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1600. }
  1601. // DELEGATE : Move
  1602. - (void)dismissMove
  1603. {
  1604. [self reloadDatasource];
  1605. }
  1606. // DELEGATE : Move
  1607. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1608. {
  1609. [_queueSelector removeAllObjects];
  1610. if ([_selectedFileIDsMetadatas count] > 0) {
  1611. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1612. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1613. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1614. } else {
  1615. _numSelectedFileIDsMetadatas = 1;
  1616. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1617. }
  1618. }
  1619. - (void)moveOpenWindow:(NSArray *)indexPaths
  1620. {
  1621. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1622. return;
  1623. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1624. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1625. viewController.delegate = self;
  1626. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1627. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1628. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1629. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1630. viewController.networkingOperationQueue = app.netQueue;
  1631. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1632. [self presentViewController:navigationController animated:YES completion:nil];
  1633. }
  1634. #pragma --------------------------------------------------------------------------------------------
  1635. #pragma mark ===== Create folder =====
  1636. #pragma --------------------------------------------------------------------------------------------
  1637. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1638. {
  1639. // Unauthorized
  1640. if (errorCode == kOCErrorServerUnauthorized)
  1641. [app openLoginView:self loginType:loginModifyPasswordUser];
  1642. if (message && errorCode != kOCErrorServerUnauthorized)
  1643. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1644. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1645. [self reloadDatasource];
  1646. // We are in directory fail ?
  1647. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1648. if (vc)
  1649. [vc.navigationController popViewControllerAnimated:YES];
  1650. }
  1651. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1652. {
  1653. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1654. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1655. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1656. if (metadata) {
  1657. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1658. metadata.fileID = metadataNet.fileID;
  1659. metadata.date = metadataNet.date;
  1660. metadata.permissions = @"RDNVCK";
  1661. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1662. [self reloadDatasource];
  1663. } else {
  1664. [self readFileReloadFolder];
  1665. }
  1666. }
  1667. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1668. {
  1669. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1670. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1671. if (![fileNameFolder length]) return;
  1672. //if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1673. //else metadataNet.serverUrl = _serverUrl;
  1674. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1675. if (!directoryID) return;
  1676. metadataNet.action = actionCreateFolder;
  1677. metadataNet.directoryID = directoryID;
  1678. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1679. metadataNet.fileName = fileNameFolder;
  1680. metadataNet.selector = selectorCreateFolder;
  1681. metadataNet.serverUrl = serverUrl;
  1682. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1683. // Create Directory on metadata
  1684. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1685. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1686. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1687. [self reloadDatasource];
  1688. }
  1689. #pragma --------------------------------------------------------------------------------------------
  1690. #pragma mark ===== Encrypted / Decrypted Folder =====
  1691. #pragma --------------------------------------------------------------------------------------------
  1692. - (void)encyptedDecryptedFolder
  1693. {
  1694. }
  1695. #pragma --------------------------------------------------------------------------------------------
  1696. #pragma mark ===== Encrypted/Decrypted File =====
  1697. #pragma --------------------------------------------------------------------------------------------
  1698. - (void)encryptedSelectedFiles
  1699. {
  1700. }
  1701. - (void)decryptedSelectedFiles
  1702. {
  1703. }
  1704. - (void)cmdEncryptedDecryptedFile
  1705. {
  1706. }
  1707. - (void)encryptedFile:(tableMetadata *)metadata
  1708. {
  1709. }
  1710. - (void)decryptedFile:(tableMetadata *)metadata
  1711. {
  1712. }
  1713. #pragma --------------------------------------------------------------------------------------------
  1714. #pragma mark ===== Progress & Task Button =====
  1715. #pragma --------------------------------------------------------------------------------------------
  1716. - (void)triggerProgressTask:(NSNotification *)notification
  1717. {
  1718. NSDictionary *dict = notification.userInfo;
  1719. NSString *fileID = [dict valueForKey:@"fileID"];
  1720. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1721. float progress = [[dict valueForKey:@"progress"] floatValue];
  1722. // CCProgress
  1723. if (progress == 0)
  1724. [self.navigationController cancelCCProgress];
  1725. else
  1726. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1727. // Check
  1728. if (!fileID || [fileID isEqualToString: @""])
  1729. return;
  1730. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1731. if (![serverUrl isEqualToString:_serverUrl])
  1732. return;
  1733. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1734. if ([self indexPathIsValid:indexPath]) {
  1735. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1736. cell.progressView.progressTintColor = [UIColor blackColor];
  1737. cell.progressView.hidden = NO;
  1738. [cell.progressView setProgress:progress];
  1739. }
  1740. }
  1741. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1742. {
  1743. UITouch * touch = [[event allTouches] anyObject];
  1744. CGPoint location = [touch locationInView:self.tableView];
  1745. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1746. if ([self indexPathIsValid:indexPath]) {
  1747. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1748. if (metadata)
  1749. [self reloadTaskButton:metadata];
  1750. }
  1751. }
  1752. - (void)reloadTaskButton:(tableMetadata *)metadata
  1753. {
  1754. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1755. __block NSURLSessionTask *findTask;
  1756. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1757. NSString *fileID = metadata.fileID;
  1758. // DOWNLOAD
  1759. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1760. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1761. for (NSURLSessionUploadTask *task in downloadTasks)
  1762. if (task.taskIdentifier == sessionTaskIdentifier) {
  1763. findTask = task;
  1764. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1765. [task cancel];
  1766. }
  1767. if (!findTask) {
  1768. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1769. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1770. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1771. }
  1772. }];
  1773. }
  1774. // UPLOAD
  1775. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1776. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1777. for (NSURLSessionUploadTask *task in uploadTasks)
  1778. if (task.taskIdentifier == sessionTaskIdentifier) {
  1779. findTask = task;
  1780. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1781. [task cancel];
  1782. }
  1783. if (!findTask) {
  1784. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1785. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1786. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1787. }
  1788. }];
  1789. }
  1790. }
  1791. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1792. {
  1793. UITouch * touch = [[event allTouches] anyObject];
  1794. CGPoint location = [touch locationInView:self.tableView];
  1795. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1796. if ([self indexPathIsValid:indexPath]) {
  1797. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1798. if (metadata)
  1799. [self cancelTaskButton:metadata reloadTable:YES];
  1800. }
  1801. }
  1802. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1803. {
  1804. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1805. __block NSURLSessionTask *findTask;
  1806. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1807. NSString *fileID = metadata.fileID;
  1808. // DOWNLOAD
  1809. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1810. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1811. for (NSURLSessionTask *task in downloadTasks)
  1812. if (task.taskIdentifier == sessionTaskIdentifier) {
  1813. findTask = task;
  1814. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1815. [task cancel];
  1816. }
  1817. if (!findTask) {
  1818. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1819. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1820. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1821. }
  1822. }];
  1823. }
  1824. // UPLOAD
  1825. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1826. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1827. for (NSURLSessionUploadTask *task in uploadTasks)
  1828. if (task.taskIdentifier == sessionTaskIdentifier) {
  1829. findTask = task;
  1830. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1831. [task cancel];
  1832. }
  1833. if (!findTask) {
  1834. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1835. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1836. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1837. }
  1838. }];
  1839. }
  1840. }
  1841. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1842. {
  1843. UITouch * touch = [[event allTouches] anyObject];
  1844. CGPoint location = [touch locationInView:self.tableView];
  1845. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1846. if ([self indexPathIsValid:indexPath]) {
  1847. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1848. if (metadata)
  1849. [self stopTaskButton:metadata];
  1850. }
  1851. }
  1852. - (void)stopTaskButton:(tableMetadata *)metadata
  1853. {
  1854. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1855. __block NSURLSessionTask *findTask;
  1856. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1857. NSString *fileID = metadata.fileID;
  1858. // UPLOAD
  1859. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1860. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1861. for (NSURLSessionUploadTask *task in uploadTasks)
  1862. if (task.taskIdentifier == sessionTaskIdentifier) {
  1863. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1864. findTask = task;
  1865. [task cancel];
  1866. }
  1867. if (!findTask) {
  1868. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1869. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1870. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1871. }
  1872. }];
  1873. }
  1874. }
  1875. #pragma --------------------------------------------------------------------------------------------
  1876. #pragma mark ===== Shared =====
  1877. #pragma --------------------------------------------------------------------------------------------
  1878. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1879. {
  1880. [_hud hideHud];
  1881. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1882. // change account ?
  1883. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1884. if([record.account isEqualToString:metadataNet.account] == NO)
  1885. return;
  1886. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1887. if (result) {
  1888. appDelegate.sharesLink = result[0];
  1889. appDelegate.sharesUserAndGroup = result[1];
  1890. }
  1891. // Notify Shares View
  1892. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1893. if (openWindow) {
  1894. if (_shareOC) {
  1895. [_shareOC reloadData];
  1896. } else {
  1897. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1898. // Apriamo la view
  1899. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1900. _shareOC.delegate = self;
  1901. _shareOC.metadata = metadata;
  1902. _shareOC.serverUrl = metadataNet.serverUrl;
  1903. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1904. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1905. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1906. [self presentViewController:_shareOC animated:YES completion:nil];
  1907. }
  1908. }
  1909. [self tableViewReloadData];
  1910. }
  1911. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1912. {
  1913. [_hud hideHud];
  1914. // Unauthorized
  1915. if (errorCode == kOCErrorServerUnauthorized)
  1916. [app openLoginView:self loginType:loginModifyPasswordUser];
  1917. if (errorCode != kOCErrorServerUnauthorized)
  1918. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1919. if (_shareOC)
  1920. [_shareOC reloadData];
  1921. [self tableViewReloadData];
  1922. }
  1923. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1924. {
  1925. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1926. metadataNet.action = actionShare;
  1927. metadataNet.fileID = metadata.fileID;
  1928. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1929. metadataNet.password = password;
  1930. metadataNet.selector = selectorShare;
  1931. metadataNet.serverUrl = serverUrl;
  1932. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1933. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1934. }
  1935. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1936. {
  1937. [_hud hideHud];
  1938. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1939. // rimuoviamo la condivisione da db
  1940. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1941. if (result) {
  1942. appDelegate.sharesLink = result[0];
  1943. appDelegate.sharesUserAndGroup = result[1];
  1944. }
  1945. if (_shareOC)
  1946. [_shareOC reloadData];
  1947. [self tableViewReloadData];
  1948. }
  1949. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1950. {
  1951. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1952. metadataNet.action = actionUnShare;
  1953. metadataNet.fileID = metadata.fileID;
  1954. metadataNet.fileName = metadata.fileName;
  1955. metadataNet.selector = selectorUnshare;
  1956. metadataNet.serverUrl = serverUrl;
  1957. metadataNet.share = share;
  1958. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1959. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1960. }
  1961. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1962. {
  1963. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1964. metadataNet.action = actionUpdateShare;
  1965. metadataNet.fileID = metadata.fileID;
  1966. metadataNet.expirationTime = expirationTime;
  1967. metadataNet.password = password;
  1968. metadataNet.selector = selectorUpdateShare;
  1969. metadataNet.serverUrl = serverUrl;
  1970. metadataNet.share = share;
  1971. metadataNet.sharePermission = permission;
  1972. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1973. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1974. }
  1975. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1976. {
  1977. [_hud hideHud];
  1978. if (_shareOC)
  1979. [_shareOC reloadUserAndGroup:items];
  1980. }
  1981. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1982. {
  1983. [_hud hideHud];
  1984. // Unauthorized
  1985. if (errorCode == kOCErrorServerUnauthorized)
  1986. [app openLoginView:self loginType:loginModifyPasswordUser];
  1987. if (errorCode != kOCErrorServerUnauthorized)
  1988. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1989. }
  1990. - (void)getUserAndGroup:(NSString *)find
  1991. {
  1992. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1993. metadataNet.action = actionGetUserAndGroup;
  1994. metadataNet.options = find;
  1995. metadataNet.selector = selectorGetUserAndGroup;
  1996. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1997. [_hud visibleIndeterminateHud];
  1998. }
  1999. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2000. {
  2001. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2002. metadataNet.action = actionShareWith;
  2003. metadataNet.fileID = metadata.fileID;
  2004. metadataNet.directoryID = directoryID;
  2005. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2006. metadataNet.serverUrl = serverUrl;
  2007. metadataNet.selector = selectorShare;
  2008. metadataNet.share = user;
  2009. metadataNet.shareeType = shareeType;
  2010. metadataNet.sharePermission = permission;
  2011. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2012. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2013. }
  2014. - (void)openWindowShare:(tableMetadata *)metadata
  2015. {
  2016. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2017. if (!serverUrl) return;
  2018. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2019. metadataNet.action = actionReadShareServer;
  2020. metadataNet.fileID = metadata.fileID;
  2021. metadataNet.fileName = metadata.fileName;
  2022. metadataNet.selector = selectorOpenWindowShare;
  2023. metadataNet.serverUrl = serverUrl;
  2024. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2025. [_hud visibleIndeterminateHud];
  2026. }
  2027. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2028. {
  2029. CGPoint location = [tapGesture locationInView:self.tableView];
  2030. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2031. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2032. if (metadata)
  2033. [self openWindowShare:metadata];
  2034. }
  2035. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2036. {
  2037. CGPoint location = [tapGesture locationInView:self.tableView];
  2038. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2039. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2040. if (metadata) {
  2041. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2042. vc.metadata = metadata;
  2043. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2044. [self presentViewController:vc animated:YES completion:nil];
  2045. }
  2046. }
  2047. #pragma --------------------------------------------------------------------------------------------
  2048. #pragma mark ===== Favorite =====
  2049. #pragma --------------------------------------------------------------------------------------------
  2050. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2051. {
  2052. _dateReadDataSource = nil;
  2053. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2054. if (_isSearchMode)
  2055. [self readFolder:metadataNet.serverUrl];
  2056. else
  2057. [self reloadDatasource:metadataNet.serverUrl];
  2058. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2059. if (metadata.directory && metadata.favorite) {
  2060. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2061. [app.activeFavorites addFavoriteFolder:dir];
  2062. }
  2063. }
  2064. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2065. {
  2066. // Unauthorized
  2067. if (errorCode == kOCErrorServerUnauthorized)
  2068. [app openLoginView:self loginType:loginModifyPasswordUser];
  2069. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2070. }
  2071. - (void)addFavorite:(tableMetadata *)metadata
  2072. {
  2073. if (metadata.directory) {
  2074. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2075. } else {
  2076. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2077. if (serverUrl)
  2078. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2079. }
  2080. }
  2081. - (void)removeFavorite:(tableMetadata *)metadata
  2082. {
  2083. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2084. }
  2085. #pragma --------------------------------------------------------------------------------------------
  2086. #pragma mark ===== Open in... =====
  2087. #pragma --------------------------------------------------------------------------------------------
  2088. - (void)openIn:(tableMetadata *)metadata
  2089. {
  2090. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2091. if (!serverUrl) return;
  2092. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2093. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2094. if ([self indexPathIsValid:indexPath])
  2095. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2096. }
  2097. #pragma --------------------------------------------------------------------------------------------
  2098. #pragma mark ===== Remove Local File =====
  2099. #pragma --------------------------------------------------------------------------------------------
  2100. - (void)removeLocalFile:(tableMetadata *)metadata
  2101. {
  2102. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2103. if (!serverUrl) return;
  2104. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2105. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2106. [self reloadDatasource:serverUrl];
  2107. }
  2108. #pragma --------------------------------------------------------------------------------------------
  2109. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2110. #pragma --------------------------------------------------------------------------------------------
  2111. - (void)orderTable:(NSString *)order
  2112. {
  2113. [CCUtility setOrderSettings:order];
  2114. // Clear data-read of DataSource
  2115. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2116. }
  2117. - (void)ascendingTable:(BOOL)ascending
  2118. {
  2119. [CCUtility setAscendingSettings:ascending];
  2120. // Clear data-read of DataSource
  2121. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2122. }
  2123. - (void)directoryOnTop:(BOOL)directoryOnTop
  2124. {
  2125. [CCUtility setDirectoryOnTop:directoryOnTop];
  2126. // Clear data-read of DataSource
  2127. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2128. }
  2129. - (void)tableGroupBy:(NSString *)groupBy
  2130. {
  2131. [CCUtility setGroupBySettings:groupBy];
  2132. // Clear data-read of DataSource
  2133. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2134. }
  2135. #pragma --------------------------------------------------------------------------------------------
  2136. #pragma mark ==== Menu LOGO ====
  2137. #pragma --------------------------------------------------------------------------------------------
  2138. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2139. {
  2140. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2141. return;
  2142. // Brand
  2143. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2144. return;
  2145. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2146. NSUInteger numInQueue = [app.netQueue operationCount];
  2147. if (numInSession+numInQueue > 0) {
  2148. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2149. return;
  2150. }
  2151. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2152. NSMutableArray *menuArray = [NSMutableArray new];
  2153. for (NSString *account in listAccount) {
  2154. if ([account isEqualToString:app.activeAccount]) continue;
  2155. CCMenuItem *item = [[CCMenuItem alloc] init];
  2156. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2157. item.argument = account;
  2158. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2159. item.target = self;
  2160. item.action = @selector(changeDefaultAccount:);
  2161. [menuArray addObject:item];
  2162. }
  2163. if ([menuArray count] == 0)
  2164. return;
  2165. OptionalConfiguration options;
  2166. Color textColor, backgroundColor;
  2167. textColor.R = 0;
  2168. textColor.G = 0;
  2169. textColor.B = 0;
  2170. backgroundColor.R = 1;
  2171. backgroundColor.G = 1;
  2172. backgroundColor.B = 1;
  2173. options.arrowSize = 9;
  2174. options.marginXSpacing = 7;
  2175. options.marginYSpacing = 10;
  2176. options.intervalSpacing = 20;
  2177. options.menuCornerRadius = 6.5;
  2178. options.maskToBackground = NO;
  2179. options.shadowOfMenu = YES;
  2180. options.hasSeperatorLine = YES;
  2181. options.seperatorLineHasInsets = YES;
  2182. options.textColor = textColor;
  2183. options.menuBackgroundColor = backgroundColor;
  2184. CGRect rect = self.view.frame;
  2185. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2186. CGFloat safeAreaTop = 0;
  2187. CGFloat offsetY = 35;
  2188. if (@available(iOS 11, *)) {
  2189. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2190. }
  2191. rect.origin.y = locationY + safeAreaTop + offsetY;
  2192. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2193. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2194. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2195. }
  2196. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2197. {
  2198. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2199. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2200. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2201. if (tableAccount)
  2202. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2203. // go to home sweet home
  2204. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2205. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2206. });
  2207. }
  2208. #pragma --------------------------------------------------------------------------------------------
  2209. #pragma mark ==== ReMenu ====
  2210. #pragma --------------------------------------------------------------------------------------------
  2211. - (void)createReMenuBackgroundView:(REMenu *)menu
  2212. {
  2213. UILayoutGuide *layoutGuide;
  2214. if (@available(iOS 11, *)) {
  2215. layoutGuide = [UIApplication sharedApplication].delegate.window.safeAreaLayoutGuide;
  2216. }
  2217. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2218. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2219. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, rootController.view.frame.size.width, rootController.view.frame.size.height);
  2220. [UIView animateWithDuration:0.2 animations:^{
  2221. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height + 40;
  2222. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, self.view.frame.size.width, - y);
  2223. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2224. }];
  2225. }
  2226. - (void)createReMainMenu
  2227. {
  2228. NSString *ordinamento;
  2229. NSString *groupBy = _directoryGroupBy;
  2230. __block NSString *nuovoOrdinamento;
  2231. NSString *titoloNuovo, *titoloAttuale;
  2232. BOOL ascendente;
  2233. __block BOOL nuovoAscendente;
  2234. UIImage *image;
  2235. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2236. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2237. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2238. [self tableViewSelect:YES];
  2239. }
  2240. }];
  2241. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2242. ordinamento = _directoryOrder;
  2243. if ([ordinamento isEqualToString:@"fileName"]) {
  2244. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2245. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2246. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2247. nuovoOrdinamento = @"date";
  2248. }
  2249. if ([ordinamento isEqualToString:@"date"]) {
  2250. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2251. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2252. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2253. nuovoOrdinamento = @"fileName";
  2254. }
  2255. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2256. [self orderTable:nuovoOrdinamento];
  2257. }];
  2258. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2259. ascendente = [CCUtility getAscendingSettings];
  2260. if (ascendente) {
  2261. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2262. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2263. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2264. nuovoAscendente = false;
  2265. }
  2266. if (!ascendente) {
  2267. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2268. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2269. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2270. nuovoAscendente = true;
  2271. }
  2272. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2273. [self ascendingTable:nuovoAscendente];
  2274. }];
  2275. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2276. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2277. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2278. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2279. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2280. else [self tableGroupBy:@"alphabetic"];
  2281. }];
  2282. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2283. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2284. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2285. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2286. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2287. else [self tableGroupBy:@"typefile"];
  2288. }];
  2289. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2290. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2291. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2292. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2293. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2294. else [self tableGroupBy:@"date"];
  2295. }];
  2296. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2297. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2298. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2299. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2300. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2301. else [self directoryOnTop:YES];
  2302. }];
  2303. // REMENU --------------------------------------------------------------------------------------------------------------
  2304. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2305. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2306. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2307. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2308. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2309. app.reMainMenu.separatorHeight = 0.5;
  2310. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2311. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2312. app.reMainMenu.textColor = [UIColor blackColor];
  2313. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2314. app.reMainMenu.textShadowColor = nil;
  2315. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2316. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2317. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2318. app.reMainMenu.highlightedSeparatorColor = nil;
  2319. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2320. app.reMainMenu.highlightedTextShadowColor = nil;
  2321. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2322. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2323. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2324. app.reMainMenu.subtitleTextShadowColor = nil;
  2325. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2326. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2327. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2328. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2329. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2330. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2331. app.reMainMenu.borderWidth = 0.3;
  2332. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2333. app.reMainMenu.animationDuration = 0.2;
  2334. app.reMainMenu.closeAnimationDuration = 0.2;
  2335. app.reMainMenu.bounce = NO;
  2336. [app.reMainMenu setClosePreparationBlock:^{
  2337. // Backgroun reMenu (Gesture)
  2338. [_reMenuBackgroundView removeFromSuperview];
  2339. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2340. }];
  2341. }
  2342. - (void)toggleReMainMenu
  2343. {
  2344. if (app.reMainMenu.isOpen) {
  2345. [app.reMainMenu close];
  2346. } else {
  2347. [self createReMainMenu];
  2348. [app.reMainMenu showFromNavigationController:self.navigationController];
  2349. // Backgroun reMenu & (Gesture)
  2350. if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
  2351. [self createReMenuBackgroundView:app.reMainMenu];
  2352. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2353. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2354. }
  2355. }
  2356. - (void)createReSelectMenu
  2357. {
  2358. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2359. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2360. [self deleteFile];
  2361. }];
  2362. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2363. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2364. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2365. }];
  2366. /*
  2367. if (app.isCryptoCloudMode) {
  2368. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2369. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2370. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2371. }];
  2372. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2373. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2374. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2375. }];
  2376. }
  2377. */
  2378. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2379. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2380. [self downloadSelectedFilesFolders];
  2381. }];
  2382. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2383. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2384. [self saveSelectedFiles];
  2385. }];
  2386. // REMENU --------------------------------------------------------------------------------------------------------------
  2387. /*
  2388. if (app.isCryptoCloudMode) {
  2389. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2390. } else {
  2391. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2392. }
  2393. */
  2394. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2395. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2396. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2397. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2398. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2399. app.reSelectMenu.separatorHeight = 0.5;
  2400. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2401. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2402. app.reSelectMenu.textColor = [UIColor blackColor];
  2403. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2404. app.reSelectMenu.textShadowColor = nil;
  2405. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2406. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2407. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2408. app.reSelectMenu.highlightedSeparatorColor = nil;
  2409. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2410. app.reSelectMenu.highlightedTextShadowColor = nil;
  2411. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2412. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2413. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2414. app.reSelectMenu.subtitleTextShadowColor = nil;
  2415. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2416. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2417. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2418. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2419. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2420. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2421. app.reSelectMenu.borderWidth = 0.3;
  2422. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2423. app.reSelectMenu.closeAnimationDuration = 0.2;
  2424. app.reSelectMenu.animationDuration = 0.2;
  2425. app.reSelectMenu.bounce = NO;
  2426. [app.reSelectMenu setClosePreparationBlock:^{
  2427. // Backgroun reMenu (Gesture)
  2428. [_reMenuBackgroundView removeFromSuperview];
  2429. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2430. }];
  2431. }
  2432. - (void)toggleReSelectMenu
  2433. {
  2434. if (app.reSelectMenu.isOpen) {
  2435. [app.reSelectMenu close];
  2436. } else {
  2437. [self createReSelectMenu];
  2438. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2439. // Backgroun reMenu & (Gesture)
  2440. if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
  2441. [self createReMenuBackgroundView:app.reSelectMenu];
  2442. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2443. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2444. }
  2445. }
  2446. #pragma --------------------------------------------------------------------------------------------
  2447. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2448. #pragma --------------------------------------------------------------------------------------------
  2449. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2450. {
  2451. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2452. UITableView *tableView = (UITableView*)self.view;
  2453. CGPoint touchPoint = [recognizer locationInView:self.view];
  2454. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2455. if ([self indexPathIsValid:indexPath])
  2456. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2457. else
  2458. _metadata = nil;
  2459. [self becomeFirstResponder];
  2460. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2461. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2462. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2463. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2464. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2465. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2466. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2467. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2468. [menuController setMenuVisible:YES animated:YES];
  2469. }
  2470. }
  2471. - (BOOL)canBecomeFirstResponder
  2472. {
  2473. return YES;
  2474. }
  2475. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2476. {
  2477. // For copy file, copy files, Open in ... :
  2478. //
  2479. // NO Directory
  2480. // NO Error Passcode
  2481. // NO In Session mode (download/upload)
  2482. // NO Template
  2483. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2484. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2485. else return NO;
  2486. }
  2487. if (@selector(copyFiles:) == action) {
  2488. if (_isSelectedMode) {
  2489. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2490. for (tableMetadata *metadata in selectedMetadatas) {
  2491. if (!metadata.directory && metadata.session.length == 0)
  2492. return YES;
  2493. }
  2494. }
  2495. return NO;
  2496. }
  2497. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2498. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2499. NSArray *items = [pasteboard items];
  2500. if ([items count] == 1) {
  2501. // Value : (NSData) fileID
  2502. NSDictionary *dic = [items objectAtIndex:0];
  2503. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2504. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2505. if (fileID) {
  2506. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2507. if (metadata) {
  2508. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2509. if (account) {
  2510. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2511. if (directoryUser)
  2512. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2513. return YES;
  2514. }
  2515. }
  2516. }
  2517. }
  2518. return NO;
  2519. }
  2520. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2521. BOOL isValid = NO;
  2522. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2523. NSArray *items = [pasteboard items];
  2524. if ([items count] <= 1) return NO;
  2525. for (NSDictionary *dic in items) {
  2526. // Value : (NSData) fileID
  2527. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2528. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2529. if (fileID) {
  2530. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2531. if (metadata) {
  2532. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2533. if (account) {
  2534. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2535. if (directoryUser) {
  2536. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2537. isValid = YES;
  2538. } else {
  2539. isValid = NO;
  2540. break;
  2541. }
  2542. } else {
  2543. isValid = NO;
  2544. break;
  2545. }
  2546. } else {
  2547. isValid = NO;
  2548. break;
  2549. }
  2550. } else {
  2551. isValid = NO;
  2552. break;
  2553. }
  2554. } else {
  2555. isValid = NO;
  2556. break;
  2557. }
  2558. }
  2559. return isValid;
  2560. }
  2561. return NO;
  2562. }
  2563. /************************************ COPY ************************************/
  2564. - (void)copyFile:(id)sender
  2565. {
  2566. // Remove all item
  2567. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2568. pasteboard.items = [[NSArray alloc] init];
  2569. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2570. [self copyFileToPasteboard:_metadata];
  2571. } else {
  2572. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2573. if (serverUrl)
  2574. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2575. }
  2576. }
  2577. - (void)copyFiles:(id)sender
  2578. {
  2579. // Remove all item
  2580. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2581. pasteboard.items = [[NSArray alloc] init];
  2582. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2583. for (tableMetadata *metadata in selectedMetadatas) {
  2584. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2585. [self copyFileToPasteboard:metadata];
  2586. } else {
  2587. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2588. if (serverUrl)
  2589. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2590. }
  2591. }
  2592. [self tableViewSelect:NO];
  2593. }
  2594. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2595. {
  2596. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2597. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2598. // Value : (NSData) fileID
  2599. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2600. [items addObject:item];
  2601. [pasteboard setItems:items];
  2602. }
  2603. /************************************ OPEN IN ... ******************************/
  2604. - (void)openinFile:(id)sender
  2605. {
  2606. [self openIn:_metadata];
  2607. }
  2608. /************************************ PASTE ************************************/
  2609. - (void)pasteFile:(id)sender
  2610. {
  2611. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2612. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2613. }
  2614. - (void)pasteFileEncrypted:(id)sender
  2615. {
  2616. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2617. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2618. }
  2619. - (void)pasteFiles:(id)sender
  2620. {
  2621. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2622. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2623. }
  2624. - (void)pasteFilesEncrypted:(id)sender
  2625. {
  2626. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2627. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2628. }
  2629. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2630. {
  2631. float timer = 0;
  2632. for (NSDictionary *dic in items) {
  2633. // Value : (NSData) fileID
  2634. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2635. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2636. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2637. if (metadata) {
  2638. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2639. if (account) {
  2640. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2641. if (directoryUser) {
  2642. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2643. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]];
  2644. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2645. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2646. });
  2647. timer += 0.1;
  2648. }
  2649. }
  2650. }
  2651. }
  2652. }
  2653. }
  2654. #pragma --------------------------------------------------------------------------------------------
  2655. #pragma mark ===== Lock Passcode =====
  2656. #pragma --------------------------------------------------------------------------------------------
  2657. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2658. {
  2659. return _failedAttempts;
  2660. }
  2661. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2662. {
  2663. return _lockUntilDate;
  2664. }
  2665. - (void)passcodeViewCloseButtonPressed:(id)sender
  2666. {
  2667. [self dismissViewControllerAnimated:YES completion:nil];
  2668. }
  2669. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2670. {
  2671. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2672. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2673. _lockUntilDate = nil;
  2674. _failedAttempts = 0;
  2675. aResultHandler(YES);
  2676. } else aResultHandler(NO);
  2677. } else aResultHandler(YES);
  2678. }
  2679. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2680. {
  2681. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2682. switch (aViewController.type) {
  2683. case BKPasscodeViewControllerCheckPasscodeType: {
  2684. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2685. // possiamo procedere alla prossima directory
  2686. [self performSegueDirectoryWithControlPasscode:false];
  2687. // avviamo la sessione Passcode Lock con now
  2688. app.sessionePasscodeLock = [NSDate date];
  2689. }
  2690. // disattivazione lock cartella
  2691. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2692. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2693. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2694. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2695. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2696. }
  2697. [self tableViewReloadData];
  2698. }
  2699. }
  2700. break;
  2701. default:
  2702. break;
  2703. }
  2704. }
  2705. - (void)comandoLockPassword
  2706. {
  2707. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2708. if (!serverUrl) return;
  2709. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2710. // se non è abilitato il Lock Passcode esci
  2711. if ([[CCUtility getBlockCode] length] == 0) {
  2712. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2713. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2714. [alertController addAction:okAction];
  2715. [self presentViewController:alertController animated:YES completion:nil];
  2716. return;
  2717. }
  2718. // se è richiesta la disattivazione si chiede la password
  2719. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2720. if (directory.lock) {
  2721. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2722. viewController.delegate = self;
  2723. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2724. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2725. viewController.inputViewTitlePassword = YES;
  2726. if ([CCUtility getSimplyBlockCode]) {
  2727. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2728. viewController.passcodeInputView.maximumLength = 6;
  2729. } else {
  2730. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2731. viewController.passcodeInputView.maximumLength = 64;
  2732. }
  2733. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2734. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2735. viewController.touchIDManager = touchIDManager;
  2736. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2737. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2738. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2739. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2740. [self presentViewController:navigationController animated:YES completion:nil];
  2741. return;
  2742. }
  2743. // ---------------- ACTIVATE PASSWORD
  2744. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2745. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2746. if ([self indexPathIsValid:indexPath])
  2747. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2748. } else {
  2749. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2750. }
  2751. }
  2752. #pragma mark -
  2753. #pragma --------------------------------------------------------------------------------------------
  2754. #pragma mark ===== Swipe Tablet -> menu =====
  2755. #pragma --------------------------------------------------------------------------------------------
  2756. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2757. {
  2758. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2759. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2760. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2761. return NO;
  2762. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2763. return NO;
  2764. else
  2765. return YES;
  2766. }
  2767. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2768. {
  2769. }
  2770. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2771. {
  2772. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2773. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2774. if (direction == MGSwipeDirectionRightToLeft) {
  2775. // Delete
  2776. if (index == 0)
  2777. [self swipeDelete:indexPath];
  2778. // More
  2779. if (index == 1)
  2780. [self swipeMore:indexPath];
  2781. }
  2782. if (direction == MGSwipeDirectionLeftToRight) {
  2783. if (_metadata.favorite)
  2784. [self removeFavorite:_metadata];
  2785. else
  2786. [self addFavorite:_metadata];
  2787. }
  2788. return YES;
  2789. }
  2790. - (void)swipeDelete:(NSIndexPath *)indexPath
  2791. {
  2792. // Directory locked ?
  2793. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2794. if (!lockServerUrl) return;
  2795. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2796. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  2797. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2798. return;
  2799. }
  2800. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2801. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2802. [self performSelector:@selector(deleteFile) withObject:nil];
  2803. }]];
  2804. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2805. [alertController dismissViewControllerAnimated:YES completion:nil];
  2806. }]];
  2807. alertController.popoverPresentationController.sourceView = self.view;
  2808. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2809. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2810. [alertController.view layoutIfNeeded];
  2811. [self presentViewController:alertController animated:YES completion:nil];
  2812. }
  2813. - (void)swipeMore:(NSIndexPath *)indexPath
  2814. {
  2815. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2816. if (!serverUrl) return;
  2817. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2818. titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2819. if (_metadata.favorite) {
  2820. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2821. } else {
  2822. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2823. }
  2824. if (_metadata.directory) {
  2825. // calcolo lockServerUrl
  2826. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2827. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2828. if (directory.lock)
  2829. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2830. else
  2831. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2832. }
  2833. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2834. // ******************************************* AHKActionSheet *******************************************
  2835. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2836. actionSheet.animationDuration = 0.2;
  2837. actionSheet.buttonHeight = 50.0;
  2838. actionSheet.cancelButtonHeight = 50.0f;
  2839. actionSheet.separatorHeight = 5.0f;
  2840. actionSheet.automaticallyTintButtonImages = @(NO);
  2841. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2842. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2843. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2844. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2845. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2846. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2847. // ******************************************* DIRECTORY *******************************************
  2848. if (_metadata.directory) {
  2849. BOOL lockDirectory = NO;
  2850. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2851. // Directory bloccata ?
  2852. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  2853. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  2854. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2855. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2856. [actionSheet addButtonWithTitle: _metadata.fileName
  2857. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  2858. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2859. height: 50.0
  2860. type: AHKActionSheetButtonTypeDisabled
  2861. handler: nil
  2862. ];
  2863. if (!lockDirectory) {
  2864. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2865. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  2866. backgroundColor:[UIColor whiteColor]
  2867. height: 50.0
  2868. type:AHKActionSheetButtonTypeDefault
  2869. handler:^(AHKActionSheet *as) {
  2870. [self openWindowShare:_metadata];
  2871. }];
  2872. }
  2873. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2874. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2875. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2876. backgroundColor:[UIColor whiteColor]
  2877. height: 50.0
  2878. type:AHKActionSheetButtonTypeDefault
  2879. handler:^(AHKActionSheet *as) {
  2880. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2881. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2882. textField.text = _metadata.fileName;
  2883. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2884. //textField.delegate = self;
  2885. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2886. }];
  2887. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2888. NSLog(@"Cancel action");
  2889. }];
  2890. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2891. UITextField *fileName = alertController.textFields.firstObject;
  2892. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2893. }];
  2894. okAction.enabled = NO;
  2895. [alertController addAction:cancelAction];
  2896. [alertController addAction:okAction];
  2897. [self presentViewController:alertController animated:YES completion:nil];
  2898. }];
  2899. }
  2900. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  2901. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2902. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  2903. backgroundColor:[UIColor whiteColor]
  2904. height: 50.0
  2905. type:AHKActionSheetButtonTypeDefault
  2906. handler:^(AHKActionSheet *as) {
  2907. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2908. }];
  2909. }
  2910. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2911. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2912. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  2913. backgroundColor:[UIColor whiteColor]
  2914. height: 50.0
  2915. type:AHKActionSheetButtonTypeDefault
  2916. handler:^(AHKActionSheet *as) {
  2917. // Settings new folder Automatatic upload
  2918. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2919. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2920. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  2921. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  2922. if (app.activeAccount.length > 0 && app.activePhotos)
  2923. [app.activePhotos reloadDatasourceForced];
  2924. [self readFolder:serverUrl];
  2925. NSLog(@"[LOG] Update Folder Photo");
  2926. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  2927. if ([autoUploadPath length] > 0) {
  2928. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2929. }
  2930. }];
  2931. }
  2932. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  2933. [actionSheet addButtonWithTitle:titoloLock
  2934. image:[UIImage imageNamed:@"actionSheetLock"]
  2935. backgroundColor:[UIColor whiteColor]
  2936. height: 50.0
  2937. type:AHKActionSheetButtonTypeEncrypted
  2938. handler:^(AHKActionSheet *as) {
  2939. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2940. }];
  2941. }
  2942. /*
  2943. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  2944. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  2945. image:[UIImage imageNamed:@"actionSheetCrypto"]
  2946. backgroundColor:[UIColor whiteColor]
  2947. height: 50.0
  2948. type:AHKActionSheetButtonTypeEncrypted
  2949. handler:^(AHKActionSheet *as) {
  2950. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  2951. }];
  2952. }
  2953. */
  2954. [actionSheet show];
  2955. }
  2956. // ******************************************* FILE *******************************************
  2957. if (!_metadata.directory) {
  2958. UIImage *iconHeader;
  2959. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2960. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  2961. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  2962. else
  2963. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2964. [actionSheet addButtonWithTitle: _metadata.fileName
  2965. image: iconHeader
  2966. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2967. height: 50.0
  2968. type: AHKActionSheetButtonTypeDisabled
  2969. handler: nil
  2970. ];
  2971. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2972. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  2973. backgroundColor:[UIColor whiteColor]
  2974. height: 50.0
  2975. type:AHKActionSheetButtonTypeDefault
  2976. handler:^(AHKActionSheet *as) {
  2977. [self openWindowShare:_metadata];
  2978. }];
  2979. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2980. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  2981. backgroundColor:[UIColor whiteColor]
  2982. height: 50.0
  2983. type:AHKActionSheetButtonTypeDefault
  2984. handler:^(AHKActionSheet *as) {
  2985. [self performSelector:@selector(openIn:) withObject:_metadata];
  2986. }];
  2987. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2988. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2989. backgroundColor:[UIColor whiteColor]
  2990. height: 50.0
  2991. type:AHKActionSheetButtonTypeDefault
  2992. handler:^(AHKActionSheet *as) {
  2993. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2994. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2995. textField.text = _metadata.fileName;
  2996. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2997. }];
  2998. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2999. NSLog(@"Cancel action");
  3000. }];
  3001. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3002. UITextField *fileName = alertController.textFields.firstObject;
  3003. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3004. }];
  3005. okAction.enabled = NO;
  3006. [alertController addAction:cancelAction];
  3007. [alertController addAction:okAction];
  3008. [self presentViewController:alertController animated:YES completion:nil];
  3009. }];
  3010. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3011. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3012. backgroundColor:[UIColor whiteColor]
  3013. height: 50.0
  3014. type:AHKActionSheetButtonTypeDefault
  3015. handler:^(AHKActionSheet *as) {
  3016. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3017. }];
  3018. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3019. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3020. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3021. backgroundColor:[UIColor whiteColor]
  3022. height: 50.0
  3023. type:AHKActionSheetButtonTypeDefault
  3024. handler:^(AHKActionSheet *as) {
  3025. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3026. }];
  3027. }
  3028. /*
  3029. if (app.isCryptoCloudMode) {
  3030. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3031. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3032. backgroundColor:[UIColor whiteColor]
  3033. height: 50.0
  3034. type:AHKActionSheetButtonTypeEncrypted
  3035. handler:^(AHKActionSheet *as) {
  3036. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3037. }];
  3038. }
  3039. */
  3040. #ifdef DEBUG
  3041. /*
  3042. [actionSheet addButtonWithTitle:@"Hide file"
  3043. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3044. backgroundColor:[UIColor whiteColor]
  3045. height: 50.0
  3046. type:AHKActionSheetButtonTypeDefault
  3047. handler:^(AHKActionSheet *as) {
  3048. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3049. [self reloadDatasource];
  3050. }];
  3051. */
  3052. #endif
  3053. [actionSheet show];
  3054. }
  3055. }
  3056. #pragma --------------------------------------------------------------------------------------------
  3057. #pragma mark - ==== Datasource ====
  3058. #pragma --------------------------------------------------------------------------------------------
  3059. - (void)clearDateReadDataSource:(NSNotification *)notification
  3060. {
  3061. _dateReadDataSource = Nil;
  3062. [self reloadDatasource];
  3063. }
  3064. - (void)reloadDatasource
  3065. {
  3066. [self reloadDatasource:_serverUrl];
  3067. }
  3068. - (void)reloadDatasource:(NSString *)serverUrl
  3069. {
  3070. // test
  3071. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3072. return;
  3073. // Search Mode
  3074. if(_isSearchMode) {
  3075. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3076. [self tableViewReloadData];
  3077. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3078. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3079. _noFilesSearchDescription = @"";
  3080. }
  3081. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3082. _noFilesSearchTitle = @"";
  3083. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3084. }
  3085. [self.tableView reloadEmptyDataSet];
  3086. return;
  3087. }
  3088. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3089. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3090. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3091. if (main) {
  3092. [main reloadDatasource];
  3093. } else {
  3094. [self tableViewReloadData];
  3095. [app.activeTransfers reloadDatasource];
  3096. }
  3097. return;
  3098. }
  3099. [app.activeTransfers reloadDatasource];
  3100. // Settaggio variabili per le ottimizzazioni
  3101. _directoryGroupBy = [CCUtility getGroupBySettings];
  3102. _directoryOrder = [CCUtility getOrderSettings];
  3103. // Controllo data lettura Data Source
  3104. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3105. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3106. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3107. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3108. _dateReadDataSource = [NSDate date];
  3109. // Data Source
  3110. NSString *sorted = _directoryOrder;
  3111. if ([sorted isEqualToString:@"fileName"])
  3112. sorted = @"fileName";
  3113. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3114. if (directoryID) {
  3115. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3116. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3117. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3118. }
  3119. } else {
  3120. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3121. }
  3122. [self tableViewReloadData];
  3123. }
  3124. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3125. {
  3126. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3127. if (selectedRows.count > 0) {
  3128. for (NSIndexPath *selectionIndex in selectedRows) {
  3129. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3130. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3131. [metadatas addObject:metadata];
  3132. }
  3133. }
  3134. return metadatas;
  3135. }
  3136. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3137. {
  3138. NSInteger section = indexPath.section + 1;
  3139. NSInteger row = indexPath.row + 1;
  3140. NSInteger totSections = [_sectionDataSource.sections count] ;
  3141. if ((totSections < section) || (section > totSections)) {
  3142. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3143. return nil;
  3144. }
  3145. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3146. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3147. if (fileIDs) {
  3148. NSInteger totRows =[fileIDs count] ;
  3149. if ((totRows < row) || (row > totRows)) {
  3150. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3151. return nil;
  3152. }
  3153. } else {
  3154. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3155. return nil;
  3156. }
  3157. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3158. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3159. return metadata;
  3160. }
  3161. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3162. {
  3163. NSInteger totSections =[_sectionDataSource.sections count] ;
  3164. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3165. return nil;
  3166. }
  3167. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3168. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3169. }
  3170. #pragma --------------------------------------------------------------------------------------------
  3171. #pragma mark - ==== Table ====
  3172. #pragma --------------------------------------------------------------------------------------------
  3173. - (void)tableViewSelect:(BOOL)edit
  3174. {
  3175. // chiudiamo eventuali swipe aperti
  3176. if (edit)
  3177. [self.tableView setEditing:NO animated:NO];
  3178. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3179. [self.tableView setEditing:edit animated:YES];
  3180. _isSelectedMode = edit;
  3181. if (edit)
  3182. [self setUINavigationBarSelected];
  3183. else
  3184. [self setUINavigationBarDefault];
  3185. [_selectedFileIDsMetadatas removeAllObjects];
  3186. [self setTitle];
  3187. }
  3188. - (void)tableViewReloadData
  3189. {
  3190. // store selected cells before relod
  3191. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3192. //store swipeOffset before relod
  3193. [_statusSwipeCell removeAllObjects];
  3194. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3195. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3196. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3197. }
  3198. // reload table view
  3199. [self.tableView reloadData];
  3200. // selected cells stored
  3201. for (NSIndexPath *path in indexPaths)
  3202. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3203. [self setTableViewFooter];
  3204. if (self.tableView.editing)
  3205. [self setTitle];
  3206. }
  3207. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3208. {
  3209. if (tableView.editing == 1) {
  3210. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3211. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3212. return NO;
  3213. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3214. return NO;
  3215. else
  3216. return YES;
  3217. } else {
  3218. [_selectedFileIDsMetadatas removeAllObjects];
  3219. }
  3220. return YES;
  3221. }
  3222. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3223. {
  3224. return 60;
  3225. }
  3226. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3227. {
  3228. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3229. }
  3230. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3231. {
  3232. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3233. }
  3234. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3235. {
  3236. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3237. NSString *sectionTitle = [sections objectAtIndex:section];
  3238. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3239. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3240. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3241. return 20.f;
  3242. }
  3243. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3244. {
  3245. float shift;
  3246. UIVisualEffectView *visualEffectView;
  3247. NSString *titleSection;
  3248. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3249. return nil;
  3250. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3251. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3252. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3253. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3254. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3255. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3256. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3257. else titleSection = NSLocalizedString(titleSection,nil);
  3258. // Format title
  3259. NSString *currentDevice = [CCUtility currentDevice];
  3260. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3261. visualEffectView = [[UIVisualEffectView alloc] init];
  3262. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3263. } else {
  3264. UIVisualEffect *blurEffect;
  3265. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3266. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3267. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3268. }
  3269. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3270. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3271. shift = - 35;
  3272. else
  3273. shift = - 20;
  3274. } else shift = - 10;
  3275. // Title
  3276. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3277. titleLabel.backgroundColor = [UIColor clearColor];
  3278. titleLabel.textColor = [UIColor blackColor];
  3279. titleLabel.font = [UIFont systemFontOfSize:12];
  3280. titleLabel.textAlignment = NSTextAlignmentLeft;
  3281. titleLabel.text = titleSection;
  3282. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3283. [visualEffectView.contentView addSubview:titleLabel];
  3284. // Elements
  3285. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3286. elementLabel.backgroundColor = [UIColor clearColor];
  3287. elementLabel.textColor = [UIColor blackColor];;
  3288. elementLabel.font = [UIFont systemFontOfSize:12];
  3289. elementLabel.textAlignment = NSTextAlignmentRight;
  3290. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3291. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3292. NSUInteger rowsCount = [metadatas count];
  3293. if (rowsCount == 0) return nil;
  3294. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3295. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3296. [visualEffectView.contentView addSubview:elementLabel];
  3297. return visualEffectView;
  3298. }
  3299. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3300. {
  3301. return [_sectionDataSource.sections indexOfObject:title];
  3302. }
  3303. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3304. {
  3305. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3306. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3307. else
  3308. return nil;
  3309. }
  3310. /*
  3311. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3312. {
  3313. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3314. }
  3315. }
  3316. */
  3317. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3318. {
  3319. NSString *typeCell;
  3320. NSString *dataFile;
  3321. NSString *lunghezzaFile;
  3322. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3323. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3324. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3325. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3326. if (!serverUrl)
  3327. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3328. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3329. else typeCell = @"CellMainTransfer";
  3330. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3331. // variable base
  3332. cell.delegate = self;
  3333. cell.indexPath = indexPath;
  3334. // separator
  3335. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3336. // change color selection
  3337. UIView *selectionColor = [[UIView alloc] init];
  3338. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3339. cell.selectedBackgroundView = selectionColor;
  3340. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3341. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3342. // ----------------------------------------------------------------------------------------------------------
  3343. // DEFAULT
  3344. // ----------------------------------------------------------------------------------------------------------
  3345. cell.file.image = nil;
  3346. cell.status.image = nil;
  3347. cell.favorite.image = nil;
  3348. cell.shared.image = nil;
  3349. cell.local.image = nil;
  3350. cell.labelTitle.enabled = YES;
  3351. cell.labelTitle.text = @"";
  3352. cell.labelInfoFile.enabled = YES;
  3353. cell.labelInfoFile.text = @"";
  3354. cell.progressView.progress = 0.0;
  3355. cell.progressView.hidden = YES;
  3356. cell.cancelTaskButton.hidden = YES;
  3357. cell.reloadTaskButton.hidden = YES;
  3358. cell.stopTaskButton.hidden = YES;
  3359. cell.labelTitle.textColor = [UIColor blackColor];
  3360. // ----------------------------------------------------------------------------------------------------------
  3361. // File Name & Folder
  3362. // ----------------------------------------------------------------------------------------------------------
  3363. // nome del file
  3364. cell.labelTitle.text = metadata.fileName;
  3365. // è una directory
  3366. if (metadata.directory) {
  3367. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3368. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3369. lunghezzaFile = @" ";
  3370. // ----------------------------------------------------------------------------------------------------------
  3371. // Favorite Folder
  3372. // ----------------------------------------------------------------------------------------------------------
  3373. if (metadata.favorite) {
  3374. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3375. }
  3376. } else {
  3377. // File
  3378. dataFile = [CCUtility dateDiff:metadata.date];
  3379. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3380. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3381. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3382. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3383. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3384. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3385. cell.local.image = [UIImage imageNamed:@"local"];
  3386. else
  3387. cell.local.image = nil;
  3388. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3389. cell.accessoryType = UITableViewCellAccessoryNone;
  3390. }
  3391. // ----------------------------------------------------------------------------------------------------------
  3392. // File Image View
  3393. // ----------------------------------------------------------------------------------------------------------
  3394. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3395. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3396. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3397. } else {
  3398. if (metadata.directory)
  3399. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3400. else
  3401. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3402. if (metadata.thumbnailExists)
  3403. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3404. }
  3405. // ----------------------------------------------------------------------------------------------------------
  3406. // Image Status cyptated & Lock Passcode
  3407. // ----------------------------------------------------------------------------------------------------------
  3408. // Directory con passcode lock attivato
  3409. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3410. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3411. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3412. cell.status.image = [UIImage imageNamed:@"passcode"];
  3413. // ----------------------------------------------------------------------------------------------------------
  3414. // Favorite
  3415. // ----------------------------------------------------------------------------------------------------------
  3416. if (metadata.favorite) {
  3417. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3418. }
  3419. // ----------------------------------------------------------------------------------------------------------
  3420. // Share
  3421. // ----------------------------------------------------------------------------------------------------------
  3422. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3423. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3424. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3425. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3426. // Aggiungiamo il Tap per le shared
  3427. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3428. // Shared with you
  3429. if (isShare) {
  3430. if (metadata.directory) {
  3431. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3432. cell.accessoryType = UITableViewCellAccessoryNone;
  3433. }
  3434. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3435. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3436. [tap setNumberOfTapsRequired:1];
  3437. cell.shared.userInteractionEnabled = YES;
  3438. [cell.shared addGestureRecognizer:tap];
  3439. }
  3440. // Mounted with you
  3441. if (isMounted) {
  3442. if (metadata.directory) {
  3443. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3444. cell.accessoryType = UITableViewCellAccessoryNone;
  3445. }
  3446. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3447. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3448. [tap setNumberOfTapsRequired:1];
  3449. cell.shared.userInteractionEnabled = YES;
  3450. [cell.shared addGestureRecognizer:tap];
  3451. }
  3452. // You share
  3453. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3454. if (metadata.directory) {
  3455. if ([shareLink length] > 0)
  3456. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3457. if ([shareUserAndGroup length] > 0)
  3458. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3459. cell.shared.userInteractionEnabled = NO;
  3460. } else {
  3461. if ([shareLink length] > 0)
  3462. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3463. if ([shareUserAndGroup length] > 0)
  3464. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3465. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3466. [tap setNumberOfTapsRequired:1];
  3467. cell.shared.userInteractionEnabled = YES;
  3468. [cell.shared addGestureRecognizer:tap];
  3469. }
  3470. }
  3471. } else {
  3472. cell.shared.userInteractionEnabled = NO;
  3473. }
  3474. // ----------------------------------------------------------------------------------------------------------
  3475. // downloadFile
  3476. // ----------------------------------------------------------------------------------------------------------
  3477. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3478. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3479. // sessionTaskIdentifier : RELOAD + STOP
  3480. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3481. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3482. cell.cancelTaskButton.hidden = NO;
  3483. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3484. cell.reloadTaskButton.hidden = NO;
  3485. }
  3486. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3487. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3488. if (progress > 0) {
  3489. cell.progressView.progressTintColor = [UIColor blackColor];
  3490. cell.progressView.progress = progress;
  3491. cell.progressView.hidden = NO;
  3492. }
  3493. // ----------------------------------------------------------------------------------------------------------
  3494. // downloadFile Error
  3495. // ----------------------------------------------------------------------------------------------------------
  3496. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3497. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3498. if ([metadata.sessionError length] == 0)
  3499. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3500. else
  3501. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3502. }
  3503. }
  3504. // ----------------------------------------------------------------------------------------------------------
  3505. // uploadFile
  3506. // ----------------------------------------------------------------------------------------------------------
  3507. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3508. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3509. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3510. cell.cancelTaskButton.hidden = NO;
  3511. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3512. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3513. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3514. cell.reloadTaskButton.hidden = NO;
  3515. cell.stopTaskButton.hidden = YES;
  3516. } else {
  3517. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3518. cell.stopTaskButton.hidden = NO;
  3519. cell.reloadTaskButton.hidden = YES;
  3520. }
  3521. // se non c'è una preview in bianconero metti l'immagine di default
  3522. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3523. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3524. cell.labelTitle.enabled = NO;
  3525. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3526. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3527. if (progress > 0) {
  3528. cell.progressView.progressTintColor = [UIColor blackColor];
  3529. cell.progressView.progress = progress;
  3530. cell.progressView.hidden = NO;
  3531. }
  3532. // ----------------------------------------------------------------------------------------------------------
  3533. // uploadFileError
  3534. // ----------------------------------------------------------------------------------------------------------
  3535. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3536. cell.labelTitle.enabled = NO;
  3537. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3538. if ([metadata.sessionError length] == 0)
  3539. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3540. else
  3541. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3542. }
  3543. }
  3544. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3545. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3546. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3547. // ======== MGSwipe ========
  3548. if (metadata.favorite)
  3549. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3550. else
  3551. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3552. cell.leftExpansion.buttonIndex = 0;
  3553. cell.leftExpansion.fillOnTrigger = NO;
  3554. //centerIconOverText
  3555. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3556. [favoriteButton centerIconOverText];
  3557. //Right
  3558. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3559. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3560. //centerIconOverText
  3561. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3562. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3563. [deleteButton centerIconOverText];
  3564. [moreButton centerIconOverText];
  3565. //restore swipeOffset after relod
  3566. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3567. if (swipeOffset < 0) {
  3568. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3569. [_statusSwipeCell removeObjectForKey:indexPath];
  3570. } else if (swipeOffset > 0) {
  3571. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3572. [_statusSwipeCell removeObjectForKey:indexPath];
  3573. }
  3574. return cell;
  3575. }
  3576. - (void)setTableViewFooter
  3577. {
  3578. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3579. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3580. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3581. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3582. UIFont *appFont = [UIFont systemFontOfSize:12];
  3583. footerLabel.font = appFont;
  3584. footerLabel.textColor = [UIColor grayColor];
  3585. footerLabel.backgroundColor = [UIColor clearColor];
  3586. footerLabel.textAlignment = NSTextAlignmentCenter;
  3587. NSString *folders;
  3588. NSString *files;
  3589. NSString *footerText;
  3590. if (_sectionDataSource.directories > 1) {
  3591. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3592. } else if (_sectionDataSource.directories == 1){
  3593. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3594. } else {
  3595. folders = @"";
  3596. }
  3597. if (_sectionDataSource.files > 1) {
  3598. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3599. } else if (_sectionDataSource.files == 1){
  3600. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3601. } else {
  3602. files = @"";
  3603. }
  3604. if ([folders isEqualToString:@""]) {
  3605. footerText = files;
  3606. } else if ([files isEqualToString:@""]) {
  3607. footerText = folders;
  3608. } else {
  3609. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3610. }
  3611. footerLabel.text = footerText;
  3612. [footerView addSubview:footerLabel];
  3613. [self.tableView setTableFooterView:footerView];
  3614. }
  3615. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3616. {
  3617. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3618. // settiamo il record file.
  3619. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3620. if (!_metadata)
  3621. return;
  3622. // se non può essere selezionata deseleziona
  3623. if ([cell isEditing] == NO)
  3624. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3625. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3626. if (self.tableView.editing) {
  3627. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3628. [self setTitle];
  3629. return;
  3630. }
  3631. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3632. if (!serverUrl) return;
  3633. // se è in corso una sessione
  3634. if ([_metadata.session length] > 0) return;
  3635. // file
  3636. if (_metadata.directory == NO) {
  3637. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3638. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3639. #ifdef DEBUG
  3640. // TEST ENCRYPTED
  3641. if ([_metadata.fileName containsString:@".dms"]) {
  3642. [[NCClientEncryption sharedManager] decryptMetadata:_metadata activeUrl:app.directoryUser];
  3643. }
  3644. #endif
  3645. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3646. } else {
  3647. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3648. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3649. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3650. }
  3651. }
  3652. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3653. }
  3654. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3655. {
  3656. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3657. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3658. [self setTitle];
  3659. }
  3660. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3661. {
  3662. if (!indexPath)
  3663. return NO;
  3664. NSInteger section = indexPath.section;
  3665. NSInteger row = indexPath.row;
  3666. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3667. if (section > lastSectionIndex || lastSectionIndex < 0)
  3668. return NO;
  3669. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3670. if (rowCount < 0)
  3671. return NO;
  3672. return row <= rowCount;
  3673. }
  3674. #pragma --------------------------------------------------------------------------------------------
  3675. #pragma mark ===== Navigation ====
  3676. #pragma --------------------------------------------------------------------------------------------
  3677. - (BOOL)shouldPerformSegue
  3678. {
  3679. // if background return
  3680. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3681. if (self.view.window == NO)
  3682. return NO;
  3683. // Collapsed ma siamo già in detail esci
  3684. if (self.splitViewController.isCollapsed)
  3685. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3686. return YES;
  3687. }
  3688. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3689. {
  3690. id viewController = segue.destinationViewController;
  3691. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3692. tableMetadata *metadata;
  3693. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3694. UINavigationController *nav = viewController;
  3695. _detailViewController = (CCDetail *)nav.topViewController;
  3696. } else {
  3697. _detailViewController = segue.destinationViewController;
  3698. }
  3699. if ([sender isKindOfClass:[tableMetadata class]]) {
  3700. metadata = sender;
  3701. [allRecordsDataSourceImagesVideos addObject:sender];
  3702. } else {
  3703. metadata = _metadata;
  3704. for (NSString *fileID in _sectionDataSource.allEtag) {
  3705. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3706. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3707. [allRecordsDataSourceImagesVideos addObject:metadata];
  3708. }
  3709. }
  3710. _detailViewController.metadataDetail = metadata;
  3711. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3712. _detailViewController.dateFilterQuery = nil;
  3713. [_detailViewController setTitle:metadata.fileName];
  3714. }
  3715. // can i go to next viewcontroller
  3716. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3717. {
  3718. NSString *nomeDir;
  3719. if(self.tableView.editing == NO) {
  3720. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3721. if (!serverUrl) return;
  3722. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3723. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3724. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3725. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3726. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3727. viewController.delegate = self;
  3728. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3729. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3730. viewController.inputViewTitlePassword = YES;
  3731. if ([CCUtility getSimplyBlockCode]) {
  3732. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3733. viewController.passcodeInputView.maximumLength = 6;
  3734. } else {
  3735. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3736. viewController.passcodeInputView.maximumLength = 64;
  3737. }
  3738. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3739. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3740. viewController.touchIDManager = touchIDManager;
  3741. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3742. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3743. //viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3744. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3745. [self presentViewController:navController animated:YES completion:nil];
  3746. return;
  3747. }
  3748. nomeDir = _metadata.fileName;
  3749. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3750. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3751. if (!viewController) {
  3752. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3753. viewController.serverUrl = serverUrlPush;
  3754. viewController.titleMain = _metadata.fileName;
  3755. viewController.textBackButton = _titleMain;
  3756. // save self
  3757. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3758. [self.navigationController pushViewController:viewController animated:YES];
  3759. } else {
  3760. if (viewController.isViewLoaded) {
  3761. // Fix : Application tried to present modally an active controller
  3762. if ([self.navigationController isBeingPresented]) {
  3763. // being presented
  3764. } else if ([self.navigationController isMovingToParentViewController]) {
  3765. // being pushed
  3766. } else {
  3767. [self.navigationController pushViewController:viewController animated:YES];
  3768. }
  3769. }
  3770. }
  3771. }
  3772. }
  3773. @end